简体   繁体   English

将参数“ a”传递给类java作为命令行参数

[英]pass parameter “a” to class java for the command line argument

public static void main(String[] args) { 公共静态void main(String [] args){

        for (String a : args) {
        System.out.println(a);
    }

public class CustomConfiguration { 公共类CustomConfiguration {

public static void readConfig(String filename) { //read from config.properties file public static void readConfig(String filename){//从config.properties文件读取

try {
        String File = filename;
        System.out.println ("ConfigFile :" + File);
String result = "";
Properties properties = new Properties();
String propFileName = filename;
InputStream inputStream = new FileInputStream(propFileName);
    }

} }

My question is how can i pass the "a" to the CustomConfiguration class? 我的问题是如何将“ a”传递给CustomConfiguration类?

As other users have pointed that out already - using propertiesFile property can make your application really flexible as you only need to change the propertiesFile content and your application will obtain the necessary information from it. 正如其他用户已经指出的那样-使用propertiesFile属性可以使您的应用程序真正具有灵活性,因为您只需要更改propertiesFile内容,您的应用程序就会从中获取必要的信息。 For example, if you had the following in your properties file: 例如,如果属性文件中包含以下内容:

myFileName=C:/gherkins
typeOfMeat=Beef
typeOfRisk=Very High

you can extract the myFileName property and get the value `C:/gherkins' in your class wherever you want. 您可以提取myFileName属性,并在需要的任何位置获取类中的值“ C:/ gherkins”。 In case you change the values in your properties file, your class doesn't have to do anything except getting the new information - easy. 万一您更改属性文件中的值,您的类无需做任何事情,除了获取新信息外,这很容易。 If you are unclear, follow this - http://crunchify.com/java-properties-file-how-to-read-config-properties-values-in-java/ 如果您不清楚,请遵循以下步骤-http://crunchify.com/java-properties-file-how-to-read-config-properties-values-in-java/

Alternatively: 或者:

You can use String[] args in main method to pass the filename you are interested in. You can use that everywhere else. 您可以在main方法中使用String[] args传递您感兴趣的文件名。您可以在其他任何地方使用该文件名。 args[0] is always the path of the class file you are running and args[1], args[2], etc. will be the extra arguments supplied to the class application. args [0]始终是您正在运行的类文件的路径,而args [1],args [2]等将作为提供给类应用程序的额外参数。 In your case you want to extract the file name by doing String myFileName = args[1]; 在您的情况下,您想通过执行String myFileName = args[1];来提取文件名String myFileName = args[1]; and use myFileName in other places. 并在其他地方使用myFileName

ps in your code the filename path is C://.. . ps在您的代码中文件名路径为C://.. You sure this // is correct? 你确定这个//是正确的? you might wanted to put C:\\\\my_file_name escaping backslash? 您可能想将C:\\\\my_file_name转义为反斜杠? or just use one forward slash? 还是只使用一个正斜杠?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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