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)
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)
| 归档时间: |
|
| 查看次数: |
143454 次 |
| 最近记录: |