Read data from a text file using Java

后端 未结 16 1583
挽巷
挽巷 2020-12-10 05:35

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,

16条回答
  •  不知归路
    2020-12-10 06:07

    public class ReadFileUsingFileInputStream {
    
    /**
    * @param args
    */
    static int ch;
    
    public static void main(String[] args) {
        File file = new File("C://text.txt");
        StringBuffer stringBuffer = new StringBuffer("");
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            try {
                while((ch = fileInputStream.read())!= -1){
                    stringBuffer.append((char)ch);  
                }
            }
            catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("File contents :");
        System.out.println(stringBuffer);
        }
    }
    

提交回复
热议问题