Java create and write to a file

author image

Java create and write file image

In Java, we can use Files.write to create and write to a file.

                              String content = "..."; 	Path path = Paths.get("/home/mkyong/test.txt");  	// string -> bytes 	Files.write(path, content.getBytes(StandardCharsets.UTF_8));                          

The Files.write also accepts an Iterable interface; it means this API can write a List to a file.

                              List<String> list = Arrays.asList("a", "b", "c"); 	Files.write(path, list);                          

Short History
Before Java 7, for writing bytes (image) to a file, we use FileOutputStream; for writing characters (text) to a file, we use FileWriter, and usually wrapped by a BufferedWriter to gain performance.

  • In Java 7, there is a new NIO class named java.nio.file.Files, and we can use Files.write() to write both bytes and characters.
  • In Java 8, we can use Files.newBufferedWriter(path) to create a BufferedWriter.
  • In Java 11, there is a new Files.writeString API to write string directly to a file.

1. Create and write to a file – Files.write

1.1 Before Java 7, we can use the classic FileWriter and BufferedWriter to write text to a file.

                              try (FileWriter fw = new FileWriter(file);        BufferedWriter bw = new BufferedWriter(fw)) {       bw.write(content);       bw.newLine();   }                          

In Java 7 and above, we can use one line Files.write to write a text to a file, and we also worry-free about closing the opened resource (file) because the Files.write will auto close the opened resource.

                              Files.write(path, content.getBytes(StandardCharsets.UTF_8));                          

1.2 The below example uses Files.write to create and write a String to a file.

FileWrite.java

                              package com.mkyong.io.file;  import java.io.*; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.List;  public class FileWrite {      private static final String NEW_LINE = System.lineSeparator();      public static void main(String[] args) throws IOException {          Path path = Paths.get("/home/mkyong/test/aaa.txt");         writeFile(path, "Hello World 1" + NEW_LINE);      }      // Java 7     private static void writeFile(Path path, String content) 				throws IOException {          // file does not exist, create and write it         // if the file exists, override the content         Files.write(path, content.getBytes(StandardCharsets.UTF_8));          // Append mode         // if the file exists, append string to the end of file.         // Files.write(path, content.getBytes(StandardCharsets.UTF_8), 				//	StandardOpenOption.CREATE, StandardOpenOption.APPEND);          // if file does not exist, throws NoSuchFileException         // if the file exists, append it         // Files.write(path, content.getBytes(StandardCharsets.UTF_8), 				//	StandardOpenOption.APPEND);     } }                          

Output

Run the 1st time, and we created a file named aaa.txt.

/home/mkyong/test/aaa.txt

                              Hello World 1                          

Run the 2nd time, we will override the file content.

/home/mkyong/test/aaa.txt

                              Hello World 1                          

For append mode, we can define both StandardOpenOption.CREATE and StandardOpenOption.APPEND.

                              Files.write(path, content.getBytes(StandardCharsets.UTF_8), 				StandardOpenOption.CREATE, StandardOpenOption.APPEND);                          

Run the 3rd time, this time with append mode enabled, we will append the new content to the end of the file.

/home/mkyong/test/aaa.txt

                              Hello World 1 Hello World 1                          

1.3. The Files.write also support Iterable, it means we can pass a List to write multiple lines to a file.

                              List<String> list = Arrays.asList("a", "b", "c");  	// Java 7 	Files.write(path, list, StandardCharsets.UTF_8);    // Java 8, default utf_8   Files.write(path, list);                          

2. Java 11 – Files.writeString

In Java 7, we need to convert the String into a byte[] before passing it to Files.write.

                              String content = "..."; 	Files.write(path, content.getBytes(StandardCharsets.UTF_8));                          

In Java 11, we can use the new API named Files.writeString to write a String or text directly to a file.

                              // Java 11   private static void writeFileJava11(Path path, String content) 			throws IOException {        // default utf_8       // file does not exists, create and write it       // if the file exists, override the content       Files.writeString(path, content);        // Append mode       // Files.writeString(path, content, 			//	StandardOpenOption.CREATE, StandardOpenOption.APPEND);   }                          

3. FileWriter + BufferedWriter

3.1 Before Java 7, the FileWriter + BufferedWriter combination is a standard solution for creating and writing characters or text to a file.

                              try (FileWriter fw = new FileWriter(file);        BufferedWriter bw = new BufferedWriter(fw)) {       bw.write(content);       bw.newLine(); // add new line, System.lineSeparator()   }  	 // append mode   try (FileWriter fw = new FileWriter(file, true);        BufferedWriter bw = new BufferedWriter(fw)) {       bw.write(content);       bw.newLine();   }                          

3.2 In Java 8, we can use the Files.newBufferedWriter to directly create a BufferedWriter object.

                              // default utf_8   try (BufferedWriter bw = Files.newBufferedWriter(path)) {       bw.write(content);       bw.newLine();   }    // append mode   try (BufferedWriter bw = Files.newBufferedWriter(path,           StandardOpenOption.CREATE, StandardOpenOption.APPEND)) {       bw.write(content);       bw.newLine();   }                          

P.S There is nothing wrong with the above FileWriter + BufferedWriter method to write a file, just the Files.write provides more clean and easy to use API.