简体   繁体   English

Java:扫描仪无法读取 .txt 文件

[英]Java: Scanner cannot read .txt file

SOLVED Sat down with my professor today for a solid 30 minutes before we figured to create the "Scanner fileInput" before the "try" line.解决了今天和我的教授坐了 30 分钟,然后我们想在“尝试”行之前创建“扫描仪文件输入”。 IT WORKED.有效。 Hope this helps someone else.希望这对其他人有帮助。

after extensive research, I have not been able to find out why the scanner does not pic up "hurricane.txt" I have it saved as a .txt in the project.经过广泛的研究,我一直无法找出为什么扫描仪没有找到“hurricane.txt”,我将它保存为项目中的 .txt。 I am using NetBeans.我正在使用 NetBeans。 Any help is appreciated!任何帮助表示赞赏!

    // Openning hurricane data file


try{
   System.out.println("Openning hurricane data file...");
   Scanner fileInput = new Scanner(new File("hurricane.txt"));
   }
   catch(FileNotFoundException e){


     System.err.println("FileNotFoundException: " + e.getMessage());
       return;
   }
   System.out.println( "File opened successfully...");
   System.out.println( "Reading file..." );

This is the output I get:这是我得到的输出:

run:
Openning hurricane data file...
FileNotFoundException: hurricane.txt (The system cannot find the file specified)
BUILD SUCCESSFUL (total time: 1 second)

Either specify the full path or place the text file in the application's working directory, which you can print out as follows:指定完整路径或将文本文件放在应用程序的工作目录中,您可以按如下方式打印出来:

final String workingDir = System.getProperty("user.dir");
System.out.println("Current working directory: " + workingDir);

Then ensure the text file is in that specific directory, and that the file name and extension match.然后确保文本文件位于该特定目录中,并且文件名和扩展名匹配。

I had the same problem yesterday.我昨天遇到了同样的问题。 The mistake i made was that i created/added a file and i called it junkfile.txt.我犯的错误是我创建/添加了一个文件,我称它为junkfile.txt。 But because i did that, the name it had was junkfile.txt.txt because the .txt extension gets added automaticly, so referring to it as junkfile.txt obviously didnt work and i got a filenotfound exception which took me a while to figure out.但是因为我这样做了,它的名字是垃圾文件.txt.txt,因为.txt扩展名是自动添加的,所以将它称为垃圾文件.txt显然不起作用,我得到了一个filenotfound异常,我花了一段时间才弄清楚.

So maybe if you use hurricane.txt.txt it will work.所以也许如果你使用hurricane.txt.txt它会起作用。

Edit: if you made a text file in the working directory of netbeans and called it hurricane.txt it will appear in the projects list as hurricane.txt.txt .编辑:如果您在 netbeans 的工作目录中创建了一个文本文件并将其命名为 hurricane.txt ,它将在项目列表中显示为 hurricane.txt.txt 。

尝试

File f = new File(this.getClass().getResource("hurricane.txt").toExternalForm());

还要确保您的 txt 文件没有奇怪的字符,例如西班牙语ñ等重音ñ ,这会导致扫描仪根本不打印任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM