Reading and writing files in Java

Icon-Folder04-Open-Yellow

In this tutorial we will see how to read and write file in Java, since it is one of the things that is very useful and used when programming. It is true that it is quite tedious and long code to be written to the file read and write because they have to use objects of classes that are not frequently used and must define several exceptions as a function of reading and writing of files is made.

Although reading and writing files it can be done in various ways, in this tutorial we are going to provide the necessary code to perform these actions, but you can also do in other ways:

Reading Files:

Let us first read the contents of the following file (named ‘readme.txt’) and to print out what we read:

Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9
Line 10

First we have to say the path or directory where the file you want to read is located. If the file you have in the folder of your project (such as project we are doing) we just put the file name, but you must specify the path where the file (eg is -> Windows: c: \\ folder \ …… \ file.txt,  Linux or Unix: \ var \ www \ …… \ file.txt ). We do this as follows:

File file = new File("readme.txt");

Once you have the file you want to read, we create an object of the “Scanner” class and we will read the file line by line. Here we see the program that we will read the file line by line and print the screen line by line the contents of the file:

import java.io.File; 
import java.util.Scanner ;

public class Readingfile  {

	public  static  void main ( String [] args )  {

		// File you want to read 
		File file = new File ("readme.txt"); 
		Scanner s = null ;

		try  { 
			// read the file contents 
			System.out.println("... read the contents of the file ..."); 
			s =  new  Scanner ( file );

			// Read the file line by line 
			while  ( s.hasNextLine())  { 
				String line = s.nextLine();  	// We keep the line on a String 
				System.out.println(line);       // We print the line 
			}

		}  catch (Exception ex)  { 
			System.out.println("Message:" + ex.getMessage()); 
		}  finally  { 
			// Close the file whether the reading was successful or not 
			try  { 
				if ( s ! =  null ) 
					s ​.close (); 
			}  catch  (Exception ex2)  { 
				System.out.println( "Message 2:"  + ex2 . getMessage()); 
			} 
		} 
	} 
}

In the code we see that our object ‘s’ in the “Scanner” class is positioning itself line by line in the file and in the loop “while” we asked him the following line if it exists.

We also see in the code as we need to define multiple exceptions, if any of them occurs, the program does not stop execution. For example we see the end of the code (in the “finally”) and whether there has been or error in reading the file, we close it.

Ultimately you have the code presented here so you can read a text file (in this case a ‘txt’) line by line.

File writing:

For writing files, we will have two ways to do this, one for writing a file without a specific encoding and another to write with a particular encoding (in this case in UTF-8 ).

In these examples we will write to the file (line by line) each of the following elements of the array:

String [] lines =  {  "one" ,  "two" ,  "three" ,  "four" ,  "five" ,  "six" ,  "Seven" ,  "..."  };

The easiest way to do this writing (by a foreach array) is presented below:

import java.io.FileWriter ;

public  class  Filewriter {

	public  static  void main ( String [] args )  {

		String [] line =  {  "one" ,  "two" ,  "three" ,  "four" ,  "five" ,  "six" ,  "Seven" ,  "..."  };

		/ ** ** WRITING Form 1 / 
		FileWriter file =  null ; 
		try  {

			file =  new  FileWriter ( "writtenfile.txt" );

			// Write line by line in the file 
			for  ( String line : lines )  { 
				file.write(line + "\ n" ); 
			}

			file.close();

		}  catch  ( Exception ex )  { 
			System.out.println ( "Message of exception:"  + ex . getMessage ()); 
		} 
	} 
}

As we see in this program, just we use an object of the “FileWriter” class in which we pass the filename. If the file does not exist we create it. Actually not only have to pass the file name, but must pass the path where you want to save the file plus the name of the file, even if we like the program, we will save the file in the project folder.

Another very important thing is that we open the file and writing in slowly (or element to element of the array) and at the end when we’ve written all closed the file (method “close ()”). Actually when writing to a file, what we do is to pass a specific content (in this case a String) and writes this in the file. It is recommended that the writing should do slowly because if you store up in a variable of type String content to write and then suddenly you write, you can make an exception excess memory if you have to write to the file is very big; therefore do as I indicated here and you will have that problem.

As a result of the implementation of this program, you will have a new file called “writtenfile.txt” with the following contents:

one
two
three
four
five
six
seven
...

The second way is to write a file with a specific coding is presented below:

import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;

public class Filewriter{

	public static void main(String[] args) {

		String[] lines = { "one", "two", "three", "four", "five", "six", "seven", "..." };

		/** writing file with utf-8 encoding  **/
		Writer out = null;
		try {
			out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("writtenfile2.txt"), "UTF-8"));
			
			// writing line by line in file
			for (String lines : lineas) {
				try {
					out.write(linea+"\n");
				} catch (IOException ex) {
					System.out.println("Writing exception message: " + ex.getMessage());
				}
			}

		} catch (UnsupportedEncodingException | FileNotFoundException ex2) {
			System.out.println("Error Message 2: " + ex2.getMessage());
		} finally {
			try {
				out.close();
			} catch (IOException ex3) {
				System.out.println("Error closing file: " + ex3.getMessage());
			}
		}
	}

}

 

This form is a bit more complex and you have to try different exceptions but allows us to write to the file in the format that you specify.

As a result we have the same content as above but in this case file with the name “writtenfile2.txt”.

2 thoughts on “Reading and writing files in Java”

  1. I think you’re are missing a closing quote in your last code block, it might be missing some code.

    What do you mean write to the file slowly?

    1. Nipun Arora

      Thanks for pointing it out @ErikCH:disqus Actually the the whole code was distorted… (corrected now)

      by writing to the file slowly i mean writing content element by element so as to prevent memory exception

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top