Write Text to Specified File

Description: Writes text to a file specified by the filename parameter. It also accepts a parameter to know if the text should be appended to the end of the file or overwrite the file. Note if you are on Java 7+, you can also use try with resources for a cleaner implementation. Requires you to import the package java.io.*
Tested Platform: Java SE 19, Windows 10
Language: Java
// Writes a string to the specified filename. If the filename doesn't exist, it is created.

public static boolean writeToFile(String filename, String text, boolean appendToFile) throws IOException {
    BufferedWriter writer = null;
        
    try {
        File fileObject = new File(filename);
        
        // If file does not exist, create new file.
        if (!fileObject.exists()) { 
            fileObject.createNewFile(); 
        }
            
        if (fileObject.canWrite()) {
            writer = new BufferedWriter(new FileWriter(fileObject, appendToFile));
            writer.write(text);
            writer.close();
            return true;
        }
    }
    finally {
        // No matter the outcome, we need to make sure the 
        // writer is closed if not properly closed before.
        if (writer != null) {
            try {
                writer.close();
            }
            catch (Exception ex) { 
                // Do Nothing 
            }
        }
    }
    return false;
}

Posted: March 20, 2023

Return to the snippets listing