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.


/**
 *
 * @author javadb.com
 */

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");
    }
}

Do you know your Java?
Take a Ten-Question-Java-Quiz!

Bookmark and Share




Need help with your Java code? It's secure and confidential.
This is how it works:
Send a detailed description of what you need help with, the more details the better. Also provide a deadline for when it has to be finished. More time means better chance of putting your request into the schedule.

If the request is serious you will shortly receive an email with the price, to which you have to respond if you accept.

Once you have accepted, the work will begin on developing your code by an experienced Java developer. When the code is finished a link to a secure payment will be sent to you.

The source code is then sent to you once the payment is completed.

IMPORTANT! The request needs to be very detailed, else it may be ignored.


Write your detailed request here:

E-mail address: