简体   繁体   中英

Java Scanner can't read from only File Name

I'm making a Java program to read some scores from a .csv file and calculate the average of those scores. To read from the file, I'm using the Scanner Class.

First, I create a scanner to read from my file:

Scanner scanner = new Scanner(new File("TempFile.csv"));

I expected this to work, but it returns a FileNotFoundException. So, I replaced TempFile.csv with the file's absolute file name.

Scanner scanner = new Scanner(new File(C:\\Users\....));

This gave me the result I wanted, and I was able to parse the file. I'm new to Java, but I know that it's bad practice to use the absolute file name.

How can I use only the short file name?

Scanner scanner = new Scanner(new File (new File("TempFile.csv").getAbsolutePath()));

使用上面。

"TempFile.csv" is a relative path. It's relative to the working directory of your java program. This directory is the value of the System property "user.dir". The following line of code gives you that value...

String workingDirectory = System.getProperty("user.dir");

Hence if you are getting FileNotFoundException , it probably means file "TempFile.csv" is not located in the working directory of your java program.

By the way, since java 8, class java.nio.file.Files contains method readAllLines . So if file "TempFile.csv" is not too big, readAllLines may be a simpler alternative to class Scanner . Note though that you still need to provide the correct path to the file when calling that method.

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