views:

295

answers:

8

I need to read a text file line by line using Java. I use available() method of FileInputStream to check and loop over the file. But while reading, the loop terminates after the line before the last one. i.e., if the file has 10lines, the loop reads only the first 9 lines. Snippet used :

while(fis.available() > 0)
{
    char c = (char)fis.read();
    .....
    .....
}
+4  A: 

How about using Scanner? I think using Scanner is easier

     private static void readFile(String fileName) {
       try {
         File file = new File(fileName);
         Scanner scanner = new Scanner(file);
         while (scanner.hasNextLine()) {
           System.out.println(scanner.nextLine());
         }
         scanner.close();
       } catch (FileNotFoundException e) {
         e.printStackTrace();
       }
     }

Read more about Java IO here

vodkhang
+5  A: 

You should not use available(). It gives no guarantees what so ever. From the API docs of available():

Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.

You would probably want to use something like

try {
    BufferedReader in = new BufferedReader(new FileReader("infilename"));
    String str;
    while ((str = in.readLine()) != null)
        process(str);
    in.close();
} catch (IOException e) {
}

(taken from http://www.exampledepot.com/egs/java.io/ReadLinesFromFile.html)

aioobe
+1 to this. This is my preferred approach too. However, the in.close() should probably reside in a finally block.
Chris Henry
I know. That however, requires another `try...catch` since `close()` itself may through `IOException`. Becomes sort of ugly for a minimal example.
aioobe
Yep. Was typing an answer halfway myself when I decided to scrape the try/catch (you beat me to the answer though).
Chris Henry
+2  A: 

If you want to read line-by-line, use a BufferedReader. It has a readLine() method which returns the line as a String, or null if the end of the file has been reached. So you can do something like:

BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String line;
while ((line = reader.readLine()) != null) {
 // Do something with line
}

(Note that this code doesn't handle exceptions or close the stream, etc)

Chris Smith
A: 

Try this just a little search in Google

import java.io.*;
class FileRead 
{
   public static void main(String args[])
  {
      try{
    // Open the file that is the first 
    // command line parameter
    FileInputStream fstream = new FileInputStream("textfile.txt");
    // Get the object of DataInputStream
    DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;
    //Read File Line By Line
    while ((strLine = br.readLine()) != null)   {
      // Print the content on the console
      System.out.println (strLine);
    }
    //Close the input stream
    in.close();
    }catch (Exception e){//Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }
  }
}
Incognito
A: 

You should use BufferedReader to read a file line by line.

kgiannakakis
A: 

Try using java.io.BufferedReader like this.

java.io.BufferedReader br = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(fileName)));
String line = null;
while ((line = br.readLine()) != null){
//Process the line
}
br.close();
RaviG
+1  A: 
String file = "/path/to/your/file.txt";

try {

    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
    String line;
    // Uncomment the line below if you want to skip the fist line (e.g if headers)
    // line = br.readLine();

    while ((line = br.readLine()) != null) {

        // do something with line

    }
    br.close();

} catch (IOException e) {
    System.out.println("ERROR: unable to read file " + file);
    e.printStackTrace();   
}
Richard
A: 

Yes, buffering should be used for better performance. Use BufferedReader OR byte[] to store your temp data.

thanks.

Paarth