[英]Getting a file from a file name passed in the command line (String[] args)
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.
因此,我的程序称为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. Scanner(String)
从指定的字符串创建扫描仪。 But you want to scan the content of a file, so you want to use the Scanner(File)
constructor. 但是您要扫描文件的内容,因此要使用
Scanner(File)
构造函数。
Change from this: 从此更改:
Scanner scan=new Scanner(args[0]);
To this: 对此:
Scanner scan = new Scanner(new File(args[0]));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.