Write a line of text to File


This code writes the string to a file. It is important to close the writer, so this is done in a finally block.

public class CustomFileWriter {
    public void writeToCustomFile(String content) throws IOException {
        File customFile = new File("customFile.txt");
        BufferedWriter customBufferedWriter = null;
        try {
            customBufferedWriter = new BufferedWriter(new FileWriter(customFile));
            customBufferedWriter.write(content);
        } finally {
            if (customBufferedWriter != null) {
                customBufferedWriter.close();
            }
        }
    }
 
    // Version ≥ Java SE 7
    public void writeToCustomFileJava7(String content) throws IOException {
        Path customFilePath = Paths.get("customFile.txt");
        try (BufferedWriter customBufferedWriter = Files.newBufferedWriter(customFilePath)) {
            customBufferedWriter.write(content);
        }
    }
}
  • writeToCustomFile(String content): This method takes a String parameter content and writes it to a file named "customFile.txt". It uses traditional try-catch-finally block for resource management, ensuring that the BufferedWriter is closed properly, even if an exception occurs during writing.
  • writeToCustomFileJava7(String content): This is an updated version of the method using Java SE 7's try-with-resources feature. It achieves the same goal as the previous method but with a more concise syntax. The BufferedWriter is automatically closed when the try block is exited, making the code cleaner and less error-prone.

Basic Programs