使用Java从文本文件读取数据 [英] Read data from a text file using Java
问题描述
available()
方法 FileInputStream
来检查和循环文件。但在读取时,循环终止在最后一行之前的行之后。即如果文件有10行,则循环只读取前9行。 使用的代码片段:
pre $
while(fis.available()> 0)
{
char c =(char)fis.read();
.....
.....
}
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屋!