使用Java从文本文件读取数据 [英] Read data from a text file using Java

查看:414
本文介绍了使用Java从文本文件读取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

pre $ while(fis.available()> 0)
{
char c =(char)fis.read();
.....
.....
}


available()。它没有提供任何保证。从 API文档 available()
$ b


返回一个 / b>

$ b $可以从这个输入流中读取(或跳过)的字节数,而不会被下一次调用这个输入流的方法阻塞。 b

您可能想要使用类似于

  try {
BufferedReader in = new BufferedReader(new FileReader(infilename));
String str; ((str = in.readLine())!= null)
process(str);
in.close();
} catch(IOException e){
}

href =http://www.exampledepot.com/egs/java.io/ReadLinesFromFile.html =noreferrer> http://www.exampledepot.com/egs/java.io/ReadLinesFromFile.html a>)


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, the loop terminates after the line before the last one. i.e., if the file has 10 lines, the loop reads only the first 9 lines. Snippet used :

while(fis.available() > 0)
{
    char c = (char)fis.read();
    .....
    .....
}

解决方案

You should not use available(). It gives no guarantees what so ever. From the API docs of available():

Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.

You would probably want to use something like

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

(taken from http://www.exampledepot.com/egs/java.io/ReadLinesFromFile.html)

这篇关于使用Java从文本文件读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆