How to read and write files in Java

  • 17 June 2016
  • ADM

 

How to read and write files in Java - images/logos/java.jpg

 

In Java is easy to read and write files using BufferedReader and BufferedWriter classes.

Example

package com.admfactory;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

public class FileOperations {

    /**
     * 
     * Method used to get the file content and add it in a array of strings
     * 
     * @param path
     *            to the file
     * @return array with all lines
     */
    public ArrayList<String> read(String path) {
	BufferedReader br = null;
	ArrayList<String> result = new ArrayList<String>();
	try {
	    /** Create the reader object */
	    br = new BufferedReader(new FileReader(path));

	    /** Parsing each line in the file */
	    String line = "";
	    while ((line = br.readLine()) != null) {
		/** Adding the lines to the array list */
		result.add(line);
	    }
	} catch (Exception e) {
	    /** Just display the error */
	    e.printStackTrace();
	} finally {
	    /** Closing the the stream */
	    if (br != null) {
		try {
		    br.close();
		} catch (IOException e) {
		    e.printStackTrace();
		}
	    }
	}
	return result;
    }

    /**
     * 
     * Method used to get the file content and add it in a array of strings
     * 
     * @param path
     *            to the file
     * @return array of all lines
     */
    public ArrayList<String> write(ArrayList<String> content, String path) {
	BufferedWriter bw = null;
	ArrayList<String> result = new ArrayList<String>();
	try {

	    File file = new File(path);
	    if (!file.exists()) {
		/** Create all parents folders if necessary */
		file.getParentFile().mkdirs();
		/** Create the file */
		file.createNewFile();
	    }

	    /** Create the reader object */
	    bw = new BufferedWriter(new FileWriter(file.getAbsoluteFile()));

	    for (int i = 0; i < content.size(); i++) {
		bw.write(content.get(i));
	    }
	    bw.close();

	} catch (Exception e) {
	    /** Just display the error */
	    e.printStackTrace();
	} finally {
	    /** Closing the the stream */
	    if (bw != null) {
		try {
		    bw.close();
		} catch (IOException e) {
		    e.printStackTrace();
		}
	    }
	}
	return result;
    }

    /**
     * main method for testing
     * 
     * @param args
     */
    public static void main(String[] args) {
	String path = "c:\\admfactory\\example.txt";
	String newLine = "\r\n";
	System.out.println("File read and write Example");

	FileOperations fo = new FileOperations();

	ArrayList<String> content = new ArrayList<String>();
	content.add("This is the first line" + newLine);
	content.add("Second line" + newLine);
	content.add("Thrird line" + newLine);

	fo.write(content, path);
	System.out.println();
	System.out.println("File Content");
	ArrayList<String> contentFile = fo.read(path);
	for (int i = 0; i < contentFile.size(); i++) {
	    String line = contentFile.get(i);
	    System.out.println(line);
	}
	System.out.println();
    }
}

For more details follow the comments within the code.

Output

File read and write Example

File Content
This is the first line
Second line
Thrird line

Also, you can open the destination folder and see the file there.

Improvements

Since Java 7 you can use try-with-resources new feature, this way the file resource will be closed automatically. To use it, change the read method with:

   /**
     * 
     * Method used to get the file content and add it in a array of strings
     * 
     * @param path
     *            to the file
     * @return array with all lines
     */
    public ArrayList<String> read(String path) {
	ArrayList<String> result = new ArrayList<String>();
	try (BufferedReader br = new BufferedReader(new FileReader(path))) {

	    /** Parsing each line in the file */
	    String line = "";
	    while ((line = br.readLine()) != null) {
		/** Adding the lines to the array list */
		result.add(line);
	    }
	} catch (Exception e) {
	    /** Just display the error */
	    e.printStackTrace();
	}
	return result;
    }

As you can notice the method is much shorter but probably the logic logic is less visible.

 

References