简体   繁体   中英

How do I read in a text file from the command line

I created a scanner to read in a text file from the first element in the command line, but it results in a FileNotFoundException . How do I format it to where it accepts this file?

Here is my code:

Scanner scanner = new Scanner(new File(args[0])); 

For example, if the file name is Hello.txt , I put Hello.txt as the first element in the command line.

Works for me. "build.xml" is a file I happen to know exists in my project's folder. Try printing the "absolute path" of the file, it'll show you where Java is looking, which might be different than what you are expecting.

public class ScratchPad {

   public static void main( String[] args ) throws Exception {
      System.out.println( new File("build.xml").exists() );
      System.out.println( new File("build.xml").getAbsoluteFile() );
   }

}

Output:

run:
true
C:\Users\Brenden\Google Drive\proj\tempj8\build.xml
BUILD SUCCESSFUL (total time: 0 seconds)

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