Java:如何通过在命令行中输入来读取文件?我已经为逐行读取文件编写了代码
我正在尝试从命令行读取文件。我已经写了一个代码,我把我的输入文件行如下Java:如何通过在命令行中输入来读取文件?我已经为逐行读取文件编写了代码,java,Java,我正在尝试从命令行读取文件。我已经写了一个代码,我把我的输入文件行如下 FileInputStream fis = new FileInputStream("C:/textfile.txt"); 相反,我想在运行java程序时在命令提示符中给出输入文件名。有人能帮我怎么做吗?谢谢。使用下面的代码 public static void main(String[] ar) { if (ar.length > 0) { String fileName = ar[0];
FileInputStream fis = new FileInputStream("C:/textfile.txt");
相反,我想在运行java程序时在命令提示符中给出输入文件名。有人能帮我怎么做吗?谢谢。使用下面的代码
public static void main(String[] ar) {
if (ar.length > 0) {
String fileName = ar[0];
if (null != fileName && !"".equals(fileName.trim())) {
try {
FileInputStream fis = new FileInputStream(fileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else {
System.out
.println("Enter a file name ith command line argument.");
}
} else {
System.out.println("Enter a file name ith command line argument.");
}
}
运行示例时,运行以下命令
java className fileName
你能解释一下为什么现有的问题和教程没有帮助吗?你可以使用Scanner类..如果你指的是命令行参数,它们在args[]数组中:因为我没有找到问题的答案。重复的问题解决不了我的问题。无论如何,谢谢你的回复。谢谢各位。另外,main方法上的私有修饰符将使程序无法运行。
Scanner s = new Scanner (System.in);//create a scanner object
String filePath= s.nextLine();//read nextLine input from consol.
FileInputStream fis = new FileInputStream(filePath);