[英]How to use command line arguments as Scanner parameter in Java
我正在编写一个程序,要求我使用 java 命令行 arguments 打开文件并在该文件中查找一些信息。 我们要访问的文件已经存在于我的项目文件目录中。 我尝试访问它们的方式是使用Scanner
并传递args[0]
,它应该是我们尝试访问的文件的名称。
以下是我到目前为止提出的代码。 现在我的代码总是会抛出
java.io.FileNotFoundException: {The Files Name} (系统找不到指定的文件)
public static void main(String[] args) {
try {
File inputedFile = new File(args[0]);
Scanner fileReader = new Scanner(inputedFile);
while (fileReader.hasNextLine()) {
String fileData = fileReader.nextLine();
System.out.println(fileData);
}
fileReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred when trying to open the file.");
e.printStackTrace();
}
}
我相信我收到此异常的原因是因为 Java 无法仅从文件名中找到文件。 Java 需要文件在我的系统上的位置才能正常工作,例如:
D:\coding-stuff\Java\CS-2420\src\comprehensive\super_simple.txt
会工作,而
super_simple.txt
不会。
这对我来说是个问题,因为我需要这段代码在多台机器上运行,而不仅仅是我自己的。 所以我的问题是如何在我的文件结构中创建到文件的“相对链接”?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.