Read Text File Using BufferedReader

Description: This function reads text files using a bufferedreader and returns the contents of the text file to the caller as a string. Requires you to import the package java.io.*
Tested Platform: Java SE 19, Windows 10
Language: Java
// Reads text files and returns the file's contents as a string variable to the caller.
public static String readTextFile(String filename) throws IOException {
    BufferedReader reader = null;
    StringBuilder strBuilder = new StringBuilder();
        
    try {
        File file = new File(filename);
            
        if (file.exists() && file.canRead()) {
            reader = new BufferedReader(new FileReader(file));
                
            String line = "";
            String lineSeperator = System.getProperty("line.separator");
                
            // Read each line of the text file into the line variable
            // until there is no more lines to read. Append a line terminator
            // to the end of each read line.
                
            while ((line = reader.readLine()) != null) {
                strBuilder.append(line + lineSeperator);
            }
        }
        else {
            throw new IOException("File cannot be found or is unable to be read.");
        }
    }
    finally {
        if (reader != null) {
            try {
                reader.close();
            }
            catch (IOException e) { 
                // Do nothing
            }
        }
    }
        
    return strBuilder.toString();
}

Posted: March 20, 2023

Return to the snippets listing