Note that each of the code samples below may throw IOException
.
(请注意,下面的每个代码示例都可能抛出IOException
。)
Try/catch/finally blocks have been omitted for brevity. (为简便起见,省略了try / catch / finally块。)
See this tutorial for information about exception handling. (有关异常处理的信息,请参见本教程 。)
Note that each of the code samples below will overwrite the file if it already exists
(请注意,下面的每个代码示例都将覆盖该文件(如果已存在))
Creating a text file:
(创建一个文本文件:)
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();
Creating a binary file:
(创建一个二进制文件:)
byte data[] = ...
FileOutputStream out = new FileOutputStream("the-file-name");
out.write(data);
out.close();
Java 7+ users can use the Files
class to write to files:
(Java 7+用户可以使用Files
类来写入文件:)
Creating a text file:
(创建一个文本文件:)
List<String> lines = Arrays.asList("The first line", "The second line");
Path file = Paths.get("the-file-name.txt");
Files.write(file, lines, StandardCharsets.UTF_8);
//Files.write(file, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);
Creating a binary file:
(创建一个二进制文件:)
byte data[] = ...
Path file = Paths.get("the-file-name");
Files.write(file, data);
//Files.write(file, data, StandardOpenOption.APPEND);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…