文本以无限循环打印。有什么方法可以避免这些?
if (eLoad) {
File file = new File("reservation.txt");
/** reading a file */
try(FileInputStream fis = new FileInputStream(file)) {
int content;
while ((content = fis.read()) != -1) {
// convert to char and display it
System.out.print((char) content);
/**print out the result contents of the file. */
}
}
catch(IOException e) {
e.printStackTrace();
}
}
显示Ooutput
Homeworkdue星期六10月10日00:00:00 PDT 2015 23:00 23
Homeworkdue星期六10月10日00:00:00 PDT 2015 23:00 23
Homeworkdue星期六10月10日00:00:00 PDT 2015 23:00 23
答案 0 :(得分:0)
if (eLoad) {
File file = new File("reservation.txt");
/** reading a file */
try(FileInputStream fis = new FileInputStream(file)) {
int content;
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String line = null;
while ((line = reader.readLine()) != null) {
// convert to char and display it
System.out.print(line);
/**print out the result contents of the file. */
}
reader.close();
}
catch(IOException e) {
e.printStackTrace();
}
}
答案 1 :(得分:0)
可以添加
System.out.print(content);
之后
System.out.print((char) content);
我在编程方面不是很了解,但可能是因为它正在读取fis.read()为ASCII值,而且它是000或003。
如果是这样,我会把
content = fis.read());
while (content != 3 && content != 0 || content == null) // if either not 3 and not 0 it doesn't run or if it isn't defined
{
// do stuff
}
为while条件
引用: "这意味着,API尝试读取一行文件,获取-1并返回EOF。" (看起来它不会返回-1)
看着: https://superuser.com/questions/789026/eof-ascii-hex-code-in-text-files
答案 2 :(得分:0)
如果您希望从文件中逐行阅读,也可以尝试
while ((line = fis.readLine()) != null) {
其余的代码看起来很好。
答案 3 :(得分:0)
{{1}}