首页 > 解决方案 > 命令行参数

问题描述

我一直在从我的学习书中做一些练习,但我似乎无法弄清楚这个特定的练习。说明是:重复练习 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!");
}

标签: javaarrayscommand-linecommand-line-arguments

解决方案


我认为你的练习只需要一个小的重构来使用命令行参数来指定要读取的文件:

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

这里我们将输入文件的名称作为参数传入。


推荐阅读