简单java程序赢得';不读取文件
我对编程非常陌生,在尝试从文本文件读取数据时遇到了很多麻烦简单java程序赢得';不读取文件,java,filenotfoundexception,Java,Filenotfoundexception,我对编程非常陌生,在尝试从文本文件读取数据时遇到了很多麻烦 我的第一个问题是试图为我的文件创建一个新的Scanner对象。我得到了一个“找不到文件”错误,除非我在文件对象后添加了.getAbsolutePath() 现在,我似乎无法从文件中读取任何数据。当我试图打印文件中的每一行时,我没有得到任何输出 我想我只是错过了一些非常明显的东西。有人能帮我吗 public static void main(String[] args) { File inputFile = new File("m
public static void main(String[] args) {
File inputFile = new File("menu.txt");
System.out.println("Reading from file" + inputFile);
Scanner inputScanner = new Scanner(inputFile.getAbsolutePath());
String answer;
while (inputScanner.hasNextLine()){
answer = inputScanner.nextLine();
System.out.println(answer);
}
}
编辑:我最初将文件对象传递到我创建的扫描仪对象中,但仍然得到错误 您的问题是,您试图使用
扫描器
读取文件,而扫描器
用于读取给定字符串中的标记(例如行)。相反,您应该使用读取器
读取您的文件:
File inputFile = new File("menu.txt");
System.out.println("Reading from file" + inputFile);
BufferedReader inputReader = new BufferedReader(new FileReader(inputFile.getAbsolutePath()));
String answer;
while ((answer = inputReader.readLine()) != null) {
System.out.println(answer);
}
更新:如果您真的想使用扫描仪,您可以使用扫描仪,但随后您需要将路径
对象传递给构造函数:
File inputFile = new File("menu.txt");
System.out.println("Reading from file" + inputFile);
Scanner inputScanner = new Scanner(inputFile);
String answer;
while (inputScanner.hasNextLine()){
answer = inputScanner.nextLine();
System.out.println(answer);
}
(请注意,我没有测试此代码。)
文件。getAbsolutePath
返回一个字符串。而扫描器(字符串)
不会从文件
(它只读取字符串
)。它是我的项目目录中的menu.txt。我甚至列出了我的项目目录中的所有文件,并且很好地打印了路径。我还尝试使用完整路径,而不仅仅是菜单。txt@ElliottFrisch:发现了更紧迫的问题:System.out.println(新文件(“menu.txt”).getAbsolutePath())代码>。我几乎可以保证完整的路径不是你想象的那样。嗨,波西米亚人,谢谢你的回复。不幸的是,完整的路径正是我所期望的。我甚至尝试将该输出(完整路径)作为文件创建的参数传递,但仍然得到FileNotFoundException。这让我感到困惑,因为扫描仪可以很好地读取文件。@HovercraftFullOfEels扫描仪可以读取文件-正确-但文件应作为路径而不是字符串提供。我会更新答案。@AleksG有一个合适的扫描器
构造函数,它接受一个文件
参数。应该不需要首先将其转换为路径。嗨,Aleks,感谢您的回复。更新后的答案实际上是我原来的答案,并给出了错误。我尝试了您的第一个解决方案,但仍然得到了FileNotFoundException,因此我开始认为问题出在实际代码之外。如果您得到了FileNotFoundException
,这意味着要么文件不存在,要么您的程序在错误的位置查找它。将System.err.println(inputFile.getAbsolutePath())
放入其中,并确保打印的内容正确。
public class Test {
//The file should be in contained within the root of your project.
// When you execute a project in eclipse, the working directory is the most top level of your project.
// Right click your project, click New>File, and make a txt file called "TheGame.txt".
private static final String FILENAME = "menu.txt";
public static void main(String[] args) {
try (BufferedReader inputFile = new BufferedReader(new FileReader(FILENAME))) {
System.out.println("Reading from file" + inputFile);
String answer;
while ((answer = inputFile.readLine()) != null) {
System.out.println(answer);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}