Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

java - 如何创建文件并用Java写入文件?(How do I create a file and write to it in Java?)

用Java创建和写入(文本)文件的最简单方法是什么?

  ask by Drew Johnson translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...