所以,首先,这是作业,尽管不是我的。这是我姐夫的。他向我寻求帮助,因为我是做计算机的,但我只从事 C++ 工作。他正在使用 System.in
将键盘输入读入文件中直到他得到 EOF
。然后,他创建了 Scanner
的实例。并调用nextLine
在实例上尝试获取 filename
并得到 NoSuchElementException
。根据 Javadoc,这意味着没有接收到任何输入,这在使用 System.in
时返回似乎是一件奇怪的事情。并在键盘上打字。我怀疑 EOF
性格在某种程度上没有被消耗。他的代码将于今晚午夜到期,并且他已经完成了其他所有事情(我建议他使用虚拟文件名并回到问题上)。
这是他的代码:
import java.util.*;
import java.io.*;
public class FileTest
{
public static void main(String[] args)
{
createFile();
readFile();
}
public static void createFile()
{
//Variables
InputStream istream;
PrintStream ostream;
istream = System.in;
ostream = System.out;
Scanner keyboard = new Scanner(System.in);
int lastEntry = 0;
final int EOF = -1;
//Asks user for filename.
try
{
String fileName;
System.out.println("Please enter the filename of the file you want to open: ");
fileName = keyboard.next();
//Creates specified file.
File currentFile = new File(fileName);
//Checks if file already exists.
while(currentFile.exists())
{
System.out.println(fileName + " already exists");
System.out.println("Error: To prevent tis file from being overwritten please enter another file name");
fileName = keyboard.nextLine();
}
//Asks user for information they want stored in file.
try
{
ostream = new PrintStream(fileName);
System.out.println("Please enter what you would like to put in the file and press Ctrl+Z when finished: ");
//Writes information to file.
try
{
while((lastEntry = istream.read()) != EOF)
ostream.write(lastEntry);
}
catch(Exception e)
{
System.out.println("Error: " +e.getMessage());
}
}
catch(Exception f)
{
System.out.println("Error: " +e.getMessage());
}
}
finally
{
}
}
public static void readFile()
{
InputStream input;
PrintStream output;
output = System.out;
int lastEntry = 0;
final int EOF = -1;
Scanner keyboard2 = new Scanner(System.in);
//Asks user for filename.
String newFile;
System.out.println("Please enter the filename of the file you want to open: ");
newFile = keyboard2.next();
}
}
他得到了NoSuchElementException
newFile = keyboard2.next()
上的错误线。我浏览了一堆例子,发现有人发帖说有这个问题,但我还没有找到解决方案,所以我想我会为他赌上我的(可疑的)声誉。有人知道他如何让它发挥作用吗?
最佳答案
控制台上的 EOF 字符表示...文件结束。这就是 Scanner 方法调用抛出 NoSuchElementException
的原因。
纯 Java 应用程序无法读取 EOF 标记之后的任何内容。
There's no way to clear it?
不在纯 Java 中。理论上你可以从 native 代码中做到这一点,但我怀疑这是否会被老师接受。
关于java - 读取 EOF 后使用 Scanner 类读取 Standard.In 时出现 NoSuchElementException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8483491/