java - 命令行参数
问题描述
我一直在从我的学习书中做一些练习,但我似乎无法弄清楚这个特定的练习。说明是:重复练习 P7.2,但允许用户在命令行上指定文件名。如果用户未指定任何文件名,则提示用户输入名称。
Ín P7.2,我已经完成,我们应该编写一个程序来读取包含文本的文件,读取每一行并将其发送到输出文件,前面是行号。基本上,我想知道的是我应该做什么?
这是我现在的代码:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter name of file for reading: ");
String fileNameReading = input.next();
System.out.print("Enter name of file for writing: ");
String fileNameWriting = input.next(); om
input.close();
File fileReading = new File(fileNameReading);
Scanner in = null;
File fileWriting = new File(fileNameWriting);
PrintWriter out = null;
try {
in = new Scanner(fileReading);
out = new PrintWriter(fileWriting); fileWriting
} catch (FileNotFoundException e1) {
System.out.println("Files are not found!");
}
int lineNumber = 1;
while (in.hasNextLine()) {
String line = in.nextLine();
out.write(String.format("/* %d */ %s%n", lineNumber, line));
lineNumber++;
}
out.close();
in.close();
System.out.println();
System.out.println("Filen was read and re-written!");
}
解决方案
我认为你的练习只需要一个小的重构来使用命令行参数来指定要读取的文件:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String fileNameReading;
// check if input file were passed as a parameter
if (args != null && args.length > 0) {
fileNameReading = args[0];
}
// if not, then prompt the user for the input filename
else {
System.out.print("Enter name of file for reading: ");
fileNameReading = input.next();
}
System.out.print("Enter name of file for writing: ");
String fileNameWriting = input.next();
// rest of your code as is
}
例如,您将运行您的代码:
java YourClass input.txt
这里我们将输入文件的名称作为参数传入。
推荐阅读
- python - Python 中的 Rijndael 填充
- python - 如何从python中的字体文件中获取字体名称(标题)
- xml - XSLT 拆分一个以逗号分隔的长字符串值
- node.js - mocha 和 chai 超过 2000 毫秒的单元测试错误。用于异步测试和钩子
- java - 大型数据集:没有一个配置的节点可用于大型数据集
- python - 如何将 Matlab 中的样条曲线转换为 python?
- kubernetes - 删除命名空间挂起自定义资源终结器
- java - 查找以 1 结尾的输入的下一个素数
- django - 如何将数据传递给基于类的视图方法?
- ios - 如何使用其 Web-API 让 IOS 应用播放 Spotify 播放列表?