简体   繁体   中英

Command line arguments

I've been doing some exercises from my study book, and I can't seem to figure out this specific one. The instructions are: repeat Exercise P7.2, but allow the user to specify the file name on the command line. If the user does not specify any file name, then prompt the user for the name.

Ín P7.2, which I've completed, we were supposed to write a program that reads a file containing text, read each line and send it to the output file, preceded by line numbers. Basically, what I'm wondering is what I'm supposed to do exactly?

This is my code right now:

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!");
}

I think your exercise just requires a small refactor to use the command line arguments to specify the file for reading:

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
}

You would run your code, for example, as:

java YourClass input.txt

Here we pass in the name of the input file as a parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM