Tuesday, October 18, 2011

Text File I/O in Java

Reading from a Text File

To read information from a text file you will need to instantiate an object from the BufferedReader class. You will also need an InputStreamReader object and a FileInputStream, but those can be instantiated as anonymous objects.

In order to use this objects, you must import them from the java.io package.
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.IOException;
To "connect" to the text file, you will need to:
BufferedReader fin = new BufferedReader(new InputStreamReader
                                       (new FileInputStream("file.txt")));
At creation the BufferedReader class throws an IOException if the string (which contains the file's path) who serves as an argument for the anonymous FileInputStream object is invalid. So, you will need to place the statement above in a try-catch block.

Once created, the BufferedReader object (which I called fin) will be able to retrieve data from the text file. The easiest way to retrieve data is by reading the text file line by line:
String line;
String pathToFile = "file.txt"
BufferedReader fin = null; 
try
 {
    fin= new BufferedReader(new InputStreamReader
                            (new FileInputStream(pathToFile)));
    do
    {
      line = fin.readLine();
      if(line==null)        //Checks if you reached end of file
        break;               //Exits the loop if end of file reached
      //TO DO CODE
    }while(line!=null);
   fin.close();             //Close the stream
  }
catch(IOException e)
{
  System.out.println(e.getMessage() +"\nProgram will be aborted");
  System.exit(0);
}
It is very important to close the stream after you no longer need it. An opened stream that is no longer used can cause your program to have an erratic behavior sometimes.

The line which you read may contain numbers or other data types which you may want to load into your specific variables. To do that you will need to use StringTokenizer class. First, the class must be imported in your program:
import java.util.StringTokenizer;
To use the StringTokenizer, you will need to instantiate an object of this type. The constructor takes as arguments the string which you want to work with and a string which contains the delimiters. The delimiters represent the characters you use to separate your fields from one another in your text.
StringTokenizer strtok = new StringTokenizer(line," ");
Let's asume that you have a text file with the following structure: name age sex

Example:
Joe 32 M

If you want to assign the data from your text file to you program's variables, you can do it like this:
string name = strtok.nextToken().toString();
int age = Integer.parseInt(strtok.nextToken().toString()),
char sex = strtok.nextToken().toString().charAt(0);

Writing to a text file
To write data to a text file, you will need to instantiate an object of the PrintStream class. You will also need a FileOutputStream object to specify the file in which you want to write. If the file does not exist, it will be created by default. It is also required to place the entire operation in a try-catch block.

You will need to import the following classes:
import java.io.PrintStream;
import java.io.FileOutputStream;
import java.io.IOException
To "connect" to the text file:
PrintStream fout = new PrintStream(new FileOutputStream("file.txt"));
Once if you have access to the text file, you can simply write to it by using the PrintStream object:
fout.print("This is on line 1\n");
fout.print("This is on line 2\n");

Also, do not forget to close the output stream when you're done writing into your file.
fout.close();

No comments:

Post a Comment

Got a question regarding something in the article? Leave me a comment and I will get back at you as soon as I can!

Related Posts Plugin for WordPress, Blogger...
Recommended Post Slide Out For Blogger