so I'm having an issue reading a file that is passed into my program through the command line. So, my program is called printFile. I do the following:
java printFile text1.txt
In my main, I have:
try{
Scanner scan=new Scanner(args[0]);
while(scan.hasNextLine())
{
System.out.println(scan.nextLine());
}
}
catch(IOException e)
{
e.printStackTrace();
}
How can I correctly get the file passed in through the command line?
Scanner(String)
creates a scanner from the specified string. But you want to scan the content of a file, so you want to use the Scanner(File)
constructor.
Change from this:
Scanner scan=new Scanner(args[0]);
To this:
Scanner scan = new Scanner(new File(args[0]));
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.