了解 jar 命令行

Understanding the jar command line

下面是将要执行的一些 java 命令:

java –jar myJARfile.jar –huff –c input_file output_file

java –jar myJARfile.jar –huff –d input_file output_file

java –jar myJARfile.jar –lzw –c input_file output_file

java –jar myJARfile.jar –lzw –d input_file output_file

我想知道如何访问每个参数 –[huff|lzw] –[d|c] 和我的 main 上的文件,以便我可以执行相应的代码。它们都被视为args吗?我会使用 args[0]、args[1]、args[2]、args[3] 来访问它们吗?或者 –[huff|lzw] –[d|c] 不被视为参数,如果是,我该如何访问它们?

这就是main()方法的args参数的作用。一种测试方法是:

public static void main(String args[]) {
    // Just for Testing args[]...
    for (String str : args) {
        System.out.println(arg);
    }
    System.exit(0);
    // --------------------------

    // --- Your method code here ---
}

对于您拥有的不同参数,您需要决定它们是否需要按特定顺序排列。如果没有,那么您将需要为此编写代码,例如,这里是处理这种情况的一种方法:

// Class member variables (possible default values should be considered)...
private static String inputFile = "";              // Input File Path and File Name  [enclosed within quotation marks if whitespaces are in path]
private static String outputFile = "";             // Output File Path and File Name  [enclosed within quotation marks if whitespaces are in path]
private static String compressionType = "";        // Alternatives: HUFFMAN  (-huff) or  LZW        (-lzw).
private static String direction = "COMPRESS";      // Alternatives: COMPRESS (-c)    or  DECOMPRESS (-d).

// The main() method...
public static void main(String args[]) {
    // Process Command-Line Arguments provided in any order...
    for (String argument : args) {
        switch (argument.toLowerCase()) {
            case "-huff":
                compressionType = "HUFFMAN";
                continue;
            case "-lzw":
                compressionType = "LZW";
                continue;
            case "-c":
                direction = "COMPRESS";
                continue;
            case "-d":
                direction = "DECOMPRESS";
                continue;
        }

        // Source (input) and Destination (output) files...
        if (new File(argument).exists() && new File(argument).isFile()) {
            inputFile = argument;
        }
        else {
            outputFile = argument;
        }
    }
    // ------------------------------------------------

    System.out.println();
    System.out.println("Input File:       " + inputFile);
    System.out.println("output File:      " + outputFile);
    System.out.println("Compression Type: " + compressionType);
    System.out.println("Direction:        " + direction);

    // Do what you want with the variables contents ....

}