使用Java从文本文件中读取数据

Sar*_*ran 9 java file-io fileinputstream

我需要使用Java逐行读取文本文件.我使用available()方法FileInputStream检查并循环文件.但是在读取时,循环在最后一行之前的行之后终止.,如果文件有10行,则循环只读取前9行.使用的片段:

while(fis.available() > 0)
{
    char c = (char)fis.read();
    .....
    .....
}
Run Code Online (Sandbox Code Playgroud)

aio*_*obe 14

你不应该使用available().它无法保证什么.来自API文档available():

返回可以从此输入流中读取(或跳过)的字节数的估计值,而不会被下一次调用此输入流的方法阻塞.

你可能想要使用类似的东西

try {
    BufferedReader in = new BufferedReader(new FileReader("infilename"));
    String str;
    while ((str = in.readLine()) != null)
        process(str);
    in.close();
} catch (IOException e) {
}
Run Code Online (Sandbox Code Playgroud)

(摘自http://www.exampledepot.com/egs/java.io/ReadLinesFromFile.html)

  • 我知道.然而,这需要另一个`try ... catch`,因为`close()`本身可能通过`IOException`.最简单的例子变得有点难看. (3认同)
  • +1给这个.这也是我的首选方法.但是,in.close()应该可以驻留在finally块中. (2认同)

vod*_*ang 11

使用Scanner怎么样?我认为使用Scanner更容易

     private static void readFile(String fileName) {
       try {
         File file = new File(fileName);
         Scanner scanner = new Scanner(file);
         while (scanner.hasNextLine()) {
           System.out.println(scanner.nextLine());
         }
         scanner.close();
       } catch (FileNotFoundException e) {
         e.printStackTrace();
       }
     }
Run Code Online (Sandbox Code Playgroud)

在此处阅读有关Java IO的更多信息