命令行参数

时间:2018-10-19 08:45:00

标签: java arrays command-line command-line-arguments

我一直在学习书中做一些练习,但似乎无法弄清楚这个特定的练习。说明如下:重复练习P7.2,但允许用户在命令行上指定文件名。如果用户未指定任何文件名,则提示用户输入文件名。

在我完成的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!");
}

1 个答案:

答案 0 :(得分:0)

我认为您的练习仅需进行少量重构即可使用命令行参数指定要读取的文件:

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

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