Please disable adblock to view this page.

← Go home

File IO in Java

java-display

May 2, 2017
Published By : Pratik Kataria
Categorised in:

Let’s check out the Code

import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileWriter;

public class FileIO {
	public static void main( String[] args ){
		String src = "example.txt"; //if this file was in a directory. Use forward slash '/'

		String dst = "exampleCopy.txt";

		//Syntax style: try with resources
		//This will allow Java to call the close() method automatically
		try( 
			FileReader fr = new FileReader(src);
			BufferedReader br = new BufferedReader(fr);
			FileWriter wrtier = new FileWriter(dst);
		 	) {

			while (true) {
				String line = br.readLine();
				if(line == null) {
					break;
				} else {
					wrtier.write(line + "\n");
				}
			}

		} catch( Exception e ) {
			e.printStackTrace();
		}

	}
}

 Output: exampleCopy.txt gets created and has the same written data as that of example.txt

Notes

  • In Java, the forward slash ( / ) is used as directory separator for all Operating Systems.
  • The file is read one line at a time.
  • If there is no string in the file then it will be null
  • We pass in the “\n” because when readLine is called we get only the line and not the line feed along with it. So we need to insert it on our own.
  • try with resources syntax was introduced in Java V7.
Pratik Kataria is a budding programmer, web designer and developer.