Java: Read/Write File

Below is the source code for reading and writing text files. Unless the file size is horrendously huge, this utility should suffice.  The source code works for all versions of Java.

package test;

import java.io.*;

public class FileReadWrite {

    public static void main(String[] arg) throws IOException {
        writeFile("C:\\temp\\b.txt", "Initial contents of this file.");
        
        String outfile = readFile("C:\\temp\\b.txt");
        System.out.println("Reading file contents: "
                + outfile);

        writeFile("C:\\temp\\b.txt", "This file has been overwritten...");

        outfile = readFile("C:\\temp\\b.txt");
        System.out.println("Reading new file contents: "
                + outfile);
    }

    public static String readFile(String filename) {
        StringBuilder contents = new StringBuilder();
        try {
            File aFile = new File(filename);
            BufferedReader input = new BufferedReader(new FileReader(aFile));
            try {
                String line = null;
                while ((line = input.readLine()) != null) {
                    contents.append(line);
                    contents.append(System.getProperty("line.separator"));
                }
            } finally {
                input.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        return contents.toString();
    }

    public static void writeFile(String filename, String aContents) {
        try {
            File aFile = new File(filename);
            Writer output = new BufferedWriter(new FileWriter(aFile));
            output.write(aContents);
            output.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

Output:
Reading file contents: Initial contents of this file.

Reading new file contents: This file has been overwritten…

Leave a Reply