Java 无限循环中的文本打印
文本以无限循环打印。有没有办法避免这些Java 无限循环中的文本打印,java,Java,文本以无限循环打印。有没有办法避免这些 if (eLoad) { File file = new File("reservation.txt"); /** reading a file */ try(FileInputStream fis = new FileInputStream(file)) { int content; while ((content = fis.read()) != -1) { // co
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();
}
}
输出显示
家庭工作日星期六2015年10月10日00:00:00 PDT 23:00 23家庭工作日星期六2015年10月10日00:00:00 PDT 23:00 23
家庭工作日星期六2015年10月10日00:00:00 PDT 23:00 23 你能补充一下吗
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
}
暂时情况
引述:
这意味着,API尝试读取一行文件get-1并返回EOF
(看起来它不会返回-1)
查看:
如果您希望逐行读取文件,也可以尝试
while ((line = fis.readLine()) != null) {
其余的代码看起来不错。您的文本文件内容是什么?以下是解决这些问题的链接。您能解释一下为什么您认为它很有用吗?因为它不是。如果文件读取结束,那么它返回null,然后停止执行,从而中断循环。所以您仍然认为
int
变量内容可以null
?哦,对不起,我误读了那一行。如果它是字符串,则它将工作。它不会,因为fis.read()
不会返回字符串。所以还有其他问题需要解决。
if (eLoad) {
File file = new File("reservation.txt");
/** reading a file */
try(FileInputStream fis = new FileInputStream(file)) {
int content;
while ((content = fis.read()) != 0) //JUST CHANGE THE -1 TO 0, THEN IT WORKS {
// convert to char and display it
System.out.print((char) content);
/**print out the result contents of the file. */
}
catch(IOException e) {
e.printStackTrace();
}
}
if (eLoad) {
File file = new File("reservation.txt");
/** reading a file */
try(FileInputStream fis = new FileInputStream(file)) {
int content;
while ((content = fis.read()) != 0) //JUST CHANGE THE -1 TO 0, THEN IT WORKS {
// convert to char and display it
System.out.print((char) content);
/**print out the result contents of the file. */
}
catch(IOException e) {
e.printStackTrace();
}
}