[英]How to detect EOF in Java?
我已经尝试了一些方法来检测我的代码中的 EOF,但它仍然无法正常工作。 我试过使用 BufferedReader、Scanner 和使用 char u001a 来标记 EOF,但对我的代码仍然没有任何意义。 这是我最后的代码:
Scanner n=new Scanner(System.in);
String input;
int counter=0;
while(n.hasNextLine())
{
input=n.nextLine();
char[] charInput=input.toCharArray();
for (int i = 0; i < input.length(); i++) {
if(charInput[i]=='"')
{
if(counter%2==0)
{
System.out.print("``");
}
else
{
System.out.print("''");
}
counter++;
}
else
{
System.out.print(charInput[i]);
}
}
System.out.print("\n");
}
该程序应该在已经到达 EOF 时停止,但我不知道为什么,由于某些原因它继续运行并导致运行时错误。 请帮忙。 顺便说一句,我是新来的,如果我的问题不是很清楚,我很抱歉,先谢谢你:)
它一直在运行,因为它没有遇到 EOF。 在流结束时:
read()
返回 -1。read(byte[])
返回-1。read(byte[], int, int)
返回 -1。readLine()
返回 null。readXXX()
抛出EOFException
。Scanner.hasNextXXX()
对任何 X 返回 false。Scanner.nextXXX()
为任何 X 抛出NoSuchElementException
。 除非您遇到过其中之一,否则您的程序还没有遇到流结束。 注意\
是一个 Ctrl/z。 不是EOF。 EOF 不是字符值。
这就是我所做的
Scanner s = new Scanner(f); //f is the file object
while(s.hasNext())
{
String ss = s.nextLine();
System.out.println(ss);
}
为我工作
特别是对于System.in
,您应该能够通过FileDescriptor.in.valid()
检查支持FileDescriptor
是否仍然打开。
简单演示:
$ cat FD.java
public class FD {
public static void main(String[] args) throws Exception {
System.out.println(java.io.FileDescriptor.in.valid());
System.in.close();
System.out.println(java.io.FileDescriptor.in.valid());
}
}
$ javac FD.java
$ java -cp . FD
true
false
您可以使用try 和 catch 。
Scanner n=new Scanner(System.in);
String input;
int counter=0;
input=n.nextLine();
try{
while(input!=null)
{
char[] charInput=input.toCharArray();
for (int i = 0; i < input.length(); i++) {
if(charInput[i]=='"')
{
if(counter%2==0)
{
System.out.print("``");
}
else
{
System.out.print("''");
}
counter++;
}
else
{
System.out.print(charInput[i]);
}
}
System.out.print("\n");
input=n.nextLine();
}
}catch(Exception e){
}
在这里,当你给Ctrl+z 时, Scanner.nextLine()
会给你NoSuchElementException
。 将此异常用作 EOF 的条件。 要处理此异常,请使用 try 和 catch。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.