Thursday, February 21, 2008

Read from file with BufferedInputStream

This example shows how to read the contents of a file using a BufferedInputStream. There are a couple of ways to do so, and in this example we use a byte array to store the data read. We loop through the file contents and fill out buffer up to the size of the buffer array until there are no more data left to read. It possible to read from the file one byte at a time, but to use a buffer is more efficient.
public class Main {
    
    /**
     * This method reads contents of a file and print it out
     */
    public void readFromFile(String filename) {
        
        BufferedInputStream bufferedInput = null;
        byte[] buffer = new byte[1024];
        
        try {
            
            //Construct the BufferedInputStream object
            bufferedInput = new BufferedInputStream(new FileInputStream(filename));
            
            int bytesRead = 0;
            
            //Keep reading from the file while there is any content
            //when the end of the stream has been reached, -1 is returned
            while ((bytesRead = bufferedInput.read(buffer)) != -1) {
                
                //Process the chunk of bytes read
                //in this case we just construct a String and print it out
                String chunk = new String(buffer, 0, bytesRead);
                System.out.print(chunk);
            }
            
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            //Close the BufferedInputStream
            try {
                if (bufferedInput != null)
                    bufferedInput.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new Main().readFromFile("myFile.txt");
    }
}
 
Blogger Template Layout Design by [ METAMUSE ] : Code Name Gadget 1.1 Power By freecode-frecode.blogger.com & blogger.com Programming Blogs - BlogCatalog Blog Directory