How To Read Text File in Java?

Below code example shows how to read the text file in java. First the file is read into inputstream.


/**********************************************************************************
 * Created on 04-2011 Copyright(c) https://kodehelp.com All Rights Reserved.
 **********************************************************************************/
package com.kodehelp.javaio;

import java.io.*;

/**
 * Created by https://kodehelp.com
 * Date: 4/28/11
 */
public class ReadTextFile {

    public static void main(String[] args) throws Exception{
        InputStream is = new FileInputStream("/demo.java");
        StringBuffer buffer = new StringBuffer();
        byte[] b = new byte[1024];
        int n;
         while ((n = is.read(b)) != -1) {
            buffer.append(new String(b, 0, n));
         }
        String str = buffer.toString();
        System.out.println(str);
    }
}