There are many ways to create and write files in Java, have you really reviewed them carefully? Here are five ways to create files in Java.

  1. Files.newBufferedWriter(Java 8)
  2. Files.write(Java 7 recommended)
  3. PrintWriter
  4. File.createNewFile
  5. FileOutputStream.write(byte[] b)The pipe flow

In fact, there are many more permutations and combinations of flows through pipes, but these five are arguably the most common and best practices.

Premise tips

In the past, when I was writing technical articles involving “stream closing” and “connection closing”, people often left comments: “Still writing technical articles, write a stream do not know close ()”. I have encountered this kind of message countless times! The try-with-resources syntax is used extensively in this article. It is a very old syntax, but it is still unknown to some people. I would like to mention that the pipe flow in the following is not closed, but closed automatically.

{// include object.close () with a try(), not manually in finally, but automatically closedCopy the code

1. Java 8 Files.newBufferedWriter

Java8 provides newBufferedWriter to create and write data to files. You can append content to a file in appending mode.

@Test void testCreateFile1() throws IOException { String fileName = "D:\\data\\test\\newFile.txt"; Path path = Paths.get(fileName); // Use the try-with-resources method to close the stream. Try (BufferedWriter writer = files. newBufferedWriter(path, Standardcharsets.utf_8)) {writer.write("Hello World - create file!!" ); } // Try (BufferedWriter writer = files. newBufferedWriter(path, standardCharsets.utf_8, StandardOpenOption. APPEND)) {writer. Write (" Hello World - letter elder brother!!!!!" ); }}Copy the code

2. Java 7 Files.write

The following way, files. write, is recommended by the author. The syntax is simple, and the bottom layer is implemented using Java NIO. It also provides appending mode to append data to existing file types. This method is the most convenient way to achieve simple text file reading and writing.

@Test void testCreateFile2() throws IOException { String fileName = "D:\\data\\test\\newFile2.txt"; Write create a file and write files.write (paths.get (fileName), "Hello World - Create file!!" .getBytes(StandardCharsets.UTF_8)); Write (paths.get (fileName), "Hello World - Antetokounmpo!!" .getBytes(StandardCharsets.UTF_8), StandardOpenOption.APPEND); }Copy the code

3. PrintWriter

PrintWriter is an old method for creating and writing files. It has been in use since JDK1.5.

@Test void testCreateFile3() throws IOException { String fileName = "D:\\data\\test\\newFile3.txt"; Try (PrintWriter writer = new PrintWriter(fileName, "Utf-8 ")) {writer.println("Hello World - create file!!" ); Writer. println("Hello World - Antetokounmpo!!" ); } // Java 10 has been improved, /*try (PrintWriter writer = new PrintWriter(fileName, StandardCharsets.UTF_8)) { writer.println("first line!" ); writer.println("second line!" ); * /}}Copy the code

4. File.createNewFile()

The createNewFile() method is relatively pure, creating a file without doing a file write. Return true if the file is successful, false if the file already exists. You can work with FileWriter to write files.

@Test void testCreateFile4() throws IOException { String fileName = "D:\\data\\test\\newFile4.txt"; File file = new File(fileName); If (file.createnewFile ()) {system.out.println (" File created successfully! ); } else {system.out.println (" the file already exists and does not need to be created again "); Try (FileWriter writer = new FileWriter(file)) {writer.write("Hello World - Create file!!" ); }}Copy the code

5. The original pipe flow method

The original approach was to use the pipe flow nesting method, but I find that this approach has a long history and is very flexible to use. If you want to add a Buffer, you’re nesting a BufferedWriter, if you want to write Java objects to a file you’re nesting an ObjectOutputStream. But the bottom line is FileOutputStream.

@Test void testCreateFile5() throws IOException { String fileName = "D:\\data\\test\\newFile5.txt"; try(FileOutputStream fos = new FileOutputStream(fileName); OutputStreamWriter osw = new OutputStreamWriter(fos); BufferedWriter bw = new BufferedWriter(osw);) {bw. Write ("Hello World - create file!!" ); bw.flush(); }}Copy the code

Welcome to my blog, where there are many fine collections

  • This article is reprinted with a credit (must be accompanied by a link, not only the text) : Antetokounmpo blog.

Feel helpful to you, help me like, share! Your support is my inexhaustible creative power! . In addition, the author recently a period of time output as follows boutique content, looking forward to your attention.

  • Spring Boot2.0 by Hand
  • Spring Security- JWT-OAUTH2
  • RBAC Authority Management System for Actual Combat Front-end and Back-end Separation
  • “Actual SpringCloud Micro-service from Bronze to King”
  • VUE Series