简体   繁体   中英

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. 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. I am using 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. 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.

So maybe if you use hurricane.txt.txt it will work.

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 .

尝试

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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