views:

84

answers:

6

While trying to do some operation with files the code goes like this,

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

I saw in a program BufferedReader and InputStreamReader were also included can you explain this with a simple example? I read in many sites about file handling but still its confusing!!!!

A: 

Take a look to this basic tutorial

Basically the BufferedReader is to read the file info. There are multiple ways of doing it and really depends of your needs.

Carlos Tasada
+1  A: 
public void printFileContentsToConsole(final String aFileName) {
 //Make a new file.
 File file = new File(aFileName);

 //Declare the reader outside the scope so we can use it
 //in the finally block.
 BufferedReader reader = null;

 try {
  reader = new BufferedReader(new FileReader(file));
  String line;

  //Read one line at a time, printing it.
  while ((line = reader.readLine()) != null) {
   System.out.println(line);
  }
 } catch (IOException e) {
  e.printStackTrace();
 } catch (Exception e) {
  e.printStackTrace();
 } finally {
  try {
   //Try to close it, this might throw an exception anyway.
   reader.close();
  } catch (Exception ex) {
   ex.printStackTrace();
  }
 }
}

Obviously, having a look at the BufferedReader and FileReader APIs will answer a lot of your questions about these particular classes.

To clarify why you would want to use a BufferedReader, the point is to efficiently read in a file, line by line.

Mike
Good example but there is a potential NPE in the finally block (the reader may be null if an error occurs in the new BufferedReader... line).
Csaba_H
+2  A: 

The File class is essentially a file descriptor which allows you to get a handle on the file, but doesn't in and of itself have methods to read the information from the file.

That is where the InputStreamReader comes in. An InputStreamReader (and more easily its subclass the FileReader) will do the reading for you (there are other ways to do it, but this is one of the easiest).

The BufferedReader will wrap the InputStreamReader and will read the file into a buffer (rather than simply converting and returning the bytes after every read invocation) allowing you to more easily read in the data.

Reese Moore
A: 

Hi.

Here is how I read a file from the disk:

Notice that all the code must be placed inside a try/catch statement, in case of FileNotFoundException for example.

try
{
    //You first have to create a reader that will be used to access the file. 
    //You create the BufferedReader from a FileReader, and you only need to specify 
    //the address of the file on your disk.
    BufferedReader br = new BufferedReader(new FileReader("fileURL"));

    String s;

    //The BufferedReader has a method "readLine" that reads the file line by line
    //When the reader reaches the end of the file, the method readLine returns null,
    //so you can control if there is some data remaining or not.
    while( (s = br.readLine()) != null )
    {
          System.out.println(s);
    }

    //Don't forget to close the reader when the process is over.
    br.close();
}
catch(Exception e)
{
    // Do some stuff
}

As I can remember, the classes BufferedReader an FileReader can be found in the package java.io;

In my opinion, this is the easiest way to read a file in Java. If you need to know how to write a file, the process is almost the same so I can give you some advice too.

Hope this helps.

Hal
A: 

Basically the java.io.File class represents a file in the file system, but doesn't contains methods to manipulate them ( other than create them or delete them )

When you have to work with them, you use other classes from the java.io package, BufferefReader and InputStreamReader are among them, but thare are others like FileInputStream.

Depending on the operation you want to perform you may use a reader or a stream ( classes ending with "Reader" or "Writer" are for text content, classes ending with "Stream" are for binary content, but of course, you can always read/write text as binary ).

Most of the times you have to "chain" a couple of these classes to perform a work. It is relevant also to notice, that most of the times, you can have very similar code to write to a sockets.

A naive example could be this:

package demo;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
import java.io.IOException;

import java.util.List;
import java.util.ArrayList;


public class ReadLines {
    public static void main( String [] args )  throws IOException { 
        File toRead = new File( args[0]);
        if( toRead.exists() ) { 
             List<String> lines = readLines( toRead );
         } else {
             System.out.println( toRead.getName() + " doesn't exists" );
         }
    }
    private static List<String> readLines( File fromFile ) throws IOException  {
          BufferedReader reader = null;

          List<String> lines = new ArrayList<String>();
          try { 
              reader = new BufferedReader( new FileReader( fromFile ) ); // chaining 
              String line  = null;
              while( ( line = reader.readLine() ) != null ) { 
                  lines.add( line );
              }
         } finally  { 
             // always close the file 
            if( reader != null )  try { 
                reader.close();
            } catch( IOException ioe ) { 
               // it's ok to ignore an exception while closing a file 
            } 
         }
         return lines;
      }
  }

I hope this code, make it clearer for you and compiles ( :P I don't have a compiler at hand )

See also:

http://download.oracle.com/javase/tutorial/essential/io/ http://download.oracle.com/javase/6/docs/api/java/io/package-summary.html http://download.oracle.com/javase/6/docs/api/java/io/Reader.html http://download.oracle.com/javase/6/docs/api/java/io/Writer.html http://download.oracle.com/javase/6/docs/api/java/io/InputStream.html http://download.oracle.com/javase/6/docs/api/java/io/OutputStream.html

OscarRyz
A: 

For sake of clarity, taken from the javadoc of InputStreamReader.java

An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset. [...] Each invocation of one of an InputStreamReader's read() methods may cause one or more bytes to be read from the underlying byte-input stream. To enable the efficient conversion of bytes to characters, more bytes may be read ahead from the underlying stream than are necessary to satisfy the current read operation.

For top efficiency, consider wrapping an InputStreamReader within a BufferedReader. For example:

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

gicappa