Java 使用命令行参数将文件传递给程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1055318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:52:43  来源:igfitidea点击:

Using command-line argument for passing files to a program

javafileargument-passing

提问by Johanna

How can I receive a file as a command-line argument?

如何接收文件作为命令行参数?

采纳答案by victor hugo

Just the path of the file is passed, inside your program use the Java File class to handle it

只传递文件的路径,在你的程序中使用 Java File 类来处理它

This takes the first parameter as the file path:

这将第一个参数作为文件路径:

import java.io.File;

public class SomeProgram {
    public static void main(String[] args) {
        if(args.length > 0) {
            File file = new File(args[0]);

            // Work with your 'file' object here
        }
    }
}

回答by cd1

in Java, the mainmethod receives an array of String as argument, as you probably have noticed. you can give another name to the parameter args, but this is the most used one.

在 Java 中,该main方法接收一个 String 数组作为参数,您可能已经注意到了。您可以为参数指定另一个名称args,但这是最常用的名称。

the array argscontains the values of what the user has typed when launching your program, after the class name. for example, to run a class named Foo, the user must type:

该数组args包含用户在启动程序时键入的值,在类名之后。例如,要运行名为 Foo 的类,用户必须键入:

[user@desktop ~]$ java Foo

[user@desktop ~]$ java Foo

everything the user types after the class name is considered to be a parameter. for example:

用户在类名后键入的所有内容都被视为参数。例如:

[user@desktop ~]$ java Foo bar baz

[user@desktop ~]$ java foo bar baz

now your program has received two parameters: barand baz. those parameters are stored in the array args. as a regular Java array, the first parameter can be retrieved by accessing args[0], the second parameter can be retrieved by accessing args[1], and so on. if you try to access an invalid position (when the user didn't type what you expected), that statement will throw an ArrayIndexOutOfBoundsException, just like it would with any array. you can check how many parameters were typed with args.length.

现在您的程序已收到两个参数:barbaz。这些参数存储在数组中args。作为一个普通的Java数组,第一个参数可以通过访问获取args[0],第二个参数可以通过访问获取args[1],以此类推。如果您尝试访问无效位置(当用户没有输入您期望的内容时),该语句将抛出一个ArrayIndexOutOfBoundsException,就像使用任何数组一样。您可以检查输入了多少参数args.length

so, back to your question. the user may inform a file name as a command line parameter and you can read that value through the argument of the mainmethod, usually called args. you have to check if he really typed something as an argument (checking the array length), and if it's ok, you access args[0]to read what he's typed. then, you may create a Fileobject based on that string, and do what you want to do with it. always check if the user typed the number of parameters you are expecting, otherwise you'll get an exception when accessing the array.

所以,回到你的问题。用户可以将文件名通知为命令行参数,您可以通过main方法的参数读取该值,通常称为args. 你必须检查他是否真的输入了一些东西作为参数(检查数组长度),如果没问题,你可以args[0]阅读他输入的内容。然后,您可以File基于该字符串创建一个对象,并用它做您想做的事情。始终检查用户是否键入了您期望的参数数量,否则在访问数组时会出现异常。

here's a full example of how to use command line parameters:

这是如何使用命令行参数的完整示例:

public class Foo {
    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("no arguments were given.");
        }
        else {
            for (String a : args) {
                System.out.println(a);
            }
        }
    }
}

this class will parse the parameters informed by the user. if he hasn't type anything, the class will print the message "no arguments were given." if he informs any number of parameters, those parameters will be shown on the screen. so, running this class with the two examples I've given on this answer, the output would be:

这个类将解析用户通知的参数。如果他没有输入任何内容,该类将打印消息“没有给出参数”。如果他通知任意数量的参数,这些参数将显示在屏幕上。所以,用我在这个答案中给出的两个例子运行这个类,输出将是:

[user@desktop ~]$ java Foo
no arguments were given.
[user@desktop ~]$ java Foo bar baz
bar
baz

[user@desktop ~]$ java Foo
没有给出参数。
[user@desktop ~]$ java foo bar baz
bar
baz

回答by ledlogic

In my opinion, best practice to try to detect args == 0 and return a list of help commands on how to use the program if no arguments are provided.

在我看来,最佳实践是尝试检测 args == 0 并在未提供参数的情况下返回有关如何使用该程序的帮助命令列表。

回答by lpapez

I saw a couple other solutions, but I think they won't work if you. For example, provide C:\Program Files\file.datas command-line argument. Then it will not work, as you only take args[0]when creating a new file.

我看到了其他几个解决方案,但我认为如果你这样做,它们将不起作用。例如,C:\Program Files\file.dat作为命令行参数提供。然后它将不起作用,因为您只args[0]在创建新文件时使用。

So you should actually do something like the following, join all parts of the given argument and then make a file from it:

因此,您实际上应该执行以下操作,连接给定参数的所有部分,然后从中创建一个文件:

import java.io.File;

public class SomeProgram {
    public static void main(String[] args) {
        String current = "";
        File lastFile = null;
        for(String str : args){
            File newFile = new File((current + " " + str).trim());
            if(newFile.exists()){
                lastFile = newFile;
            }
        current += " " + str;
        }
        File yourFile = lastFile;
    }
}

I am currently working on a similar problem and this seems to do the trick.

我目前正在处理类似的问题,这似乎可以解决问题。