Java Write to File [AI Examples] To write a file in Java, several classes can be utilized depending on the specific requirements, such as writing text or binary data, and whether appending to an existing file is desired. 1. Using FileWriter (for text files): Java import java.io.FileWriter; import java.io.IOException; public class WriteToFileExample { public static void main(String[] args) { try { // Create a FileWriter object. The second argument 'true' enables append mode. // If not provided or 'false', the file will be overwritten if it exists. FileWriter writer = new FileWriter("output.txt", false); // Overwrites the file // FileWriter writer = new FileWriter("output.txt", true); // Appends to the file writer.write("This is the first line.\n"); writer.write("This is the second line."); writer.close(); // Important: Close the writer to ensure data is written to the file System.out.println("Successfully wrote to the file."); } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); } } } 2. Using BufferedWriter (for efficient text writing): Java import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class WriteWithBufferedWriter { public static void main(String[] args) { try { FileWriter fileWriter = new FileWriter("buffered_output.txt"); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter); bufferedWriter.write("This line is written using BufferedWriter."); bufferedWriter.newLine(); // Writes a new line character bufferedWriter.write("Another line."); bufferedWriter.close(); // Closes the BufferedWriter and underlying FileWriter System.out.println("Successfully wrote to the file using BufferedWriter."); } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); } } } 3. Using FileOutputStream (for binary data or raw bytes): Java import java.io.FileOutputStream; import java.io.IOException; public class WriteBinaryFile { public static void main(String[] args) { String data = "Hello, binary world!"; try { FileOutputStream fos = new FileOutputStream("binary_output.dat"); fos.write(data.getBytes()); // Writes the byte representation of the string fos.close(); System.out.println("Successfully wrote binary data to the file."); } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); } } } Key Considerations: Error Handling: File operations can throw IOException, so it is crucial to wrap the file writing logic within try-catch blocks to handle potential errors. Closing Resources: Always close the Writer or OutputStream after writing to ensure that all data is flushed to the file and system resources are released. This can be done explicitly with close() or automatically using a try-with-resources statement (available from Java 7). Append Mode: When creating a FileWriter, passing true as the second argument to the constructor enables append mode, adding new content to the end of an existing file instead of overwriting it. New Lines: For text files, use \n (newline character) or BufferedWriter.newLine() to insert line breaks. File Paths: When specifying the file name, a simple name like "output.txt" will create the file in the project's root directory. A full or relative path can be provided for different locations. [Digital Ocean Example] java write to file, write file in javaLet’s have a brief look at four options we have for java write to file operation. FileWriter: FileWriter is the simplest way to write a file in Java. It provides overloaded write method to write int, byte array, and String to the File. You can also write part of the String or byte array using FileWriter. FileWriter writes directly into Files and should be used only when the number of writes is less. BufferedWriter: BufferedWriter is almost similar to FileWriter but it uses internal buffer to write data into File. So if the number of write operations is more, the actual IO operations are less and performance is better. You should use BufferedWriter when the number of write operations is more. FileOutputStream: FileWriter and BufferedWriter are meant to write text to the file but when you need raw stream data to be written into file, you should use FileOutputStream to write file in java. Files: Java 7 introduced Files utility class and we can write a file using its write function. Internally it’s using OutputStream to write byte array into file. Java Write to File Example Here is the example showing how we can write a file in java using FileWriter, BufferedWriter, FileOutputStream, and Files in java. WriteFile.java package com.journaldev.files; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Paths; public class WriteFile { /** * This class shows how to write file in java * @param args * @throws IOException */ public static void main(String[] args) { String data = "I will write this String to File in Java"; int noOfLines = 10000; writeUsingFileWriter(data); writeUsingBufferedWriter(data, noOfLines); writeUsingFiles(data); writeUsingOutputStream(data); System.out.println("DONE"); } /** * Use Streams when you are dealing with raw data * @param data */ private static void writeUsingOutputStream(String data) { OutputStream os = null; try { os = new FileOutputStream(new File("/Users/pankaj/os.txt")); os.write(data.getBytes(), 0, data.length()); } catch (IOException e) { e.printStackTrace(); }finally{ try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * Use Files class from Java 1.7 to write files, internally uses OutputStream * @param data */ private static void writeUsingFiles(String data) { try { Files.write(Paths.get("/Users/pankaj/files.txt"), data.getBytes()); } catch (IOException e) { e.printStackTrace(); } } /** * Use BufferedWriter when number of write operations are more * It uses internal buffer to reduce real IO operations and saves time * @param data * @param noOfLines */ private static void writeUsingBufferedWriter(String data, int noOfLines) { File file = new File("/Users/pankaj/BufferedWriter.txt"); FileWriter fr = null; BufferedWriter br = null; String dataWithNewLine=data+System.getProperty("line.separator"); try{ fr = new FileWriter(file); br = new BufferedWriter(fr); for(int i = noOfLines; i>0; i--){ br.write(dataWithNewLine); } } catch (IOException e) { e.printStackTrace(); }finally{ try { br.close(); fr.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * Use FileWriter when number of write operations are less * @param data */ private static void writeUsingFileWriter(String data) { File file = new File("/Users/pankaj/FileWriter.txt"); FileWriter fr = null; try { fr = new FileWriter(file); fr.write(data); } catch (IOException e) { e.printStackTrace(); }finally{ //close resources try { fr.close(); } catch (IOException e) { e.printStackTrace(); } } } } These are the standard methods to write a file in java and you should choose any one of these based on your project requirements. That’s all for Java write to file example.