0

I want to read an entire file into a string. The file however is in the program arguments. I have been trying to use Scanner in order to:

Scanner scan = new Scanner(args[0]);  
        scan.useDelimiter("\\Z");  
        String content = scan.next(); 
        System.out.println(content);

My result is just the name of the file that is in "args[0]" instead of the actual contents of the file.

I figured a loop would not work since I am not hardcoding the file into the program.

JeffLA26
  • 13
  • 2

1 Answers1

1

Correct. If you want a Scanner wrapping a File pass a File in the constructor. Change this

Scanner scan = new Scanner(args[0]); 

to

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

The constructor for Scanner(String) says,

Constructs a new Scanner that produces values scanned from the specified string.

While the constructor for Scanner(File) says,

Constructs a new Scanner that produces values scanned from the specified file.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249