Read data from a text file using Java

后端 未结 16 1537
挽巷
挽巷 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 05:58

    String file = "/path/to/your/file.txt";
    
    try {
    
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
        String line;
        // Uncomment the line below if you want to skip the fist line (e.g if headers)
        // line = br.readLine();
    
        while ((line = br.readLine()) != null) {
    
            // do something with line
    
        }
        br.close();
    
    } catch (IOException e) {
        System.out.println("ERROR: unable to read file " + file);
        e.printStackTrace();   
    }
    

提交回复
热议问题