2017-04-11 25 views
0

int[]を入力するメソッドがあります。Javaプロパティファイルからint []を読み取る

methodABC(int[] nValue) 

私は、configファイルからこれを読みますか、私は別の形式でこれを保管しなければならないのはどのよう

nValue=1,2,3 

JavaプロパティファイルからこのnValueを利用したいと思いますか?我々はこれを行うにはどうすればよい

int nValue = Integer.parseInt(configuration.getProperty("nnValue")); 

:私が試した何

は(changing the nValue to 123 instead of 1,2,3)ですか?あなたは、これは持っている場合

+0

重複しているかどうかわかりませんが、これは面白いかもしれません:http://stackoverflow.com/questions/7015491/better-way-to-represent-array-in-java-properties-file – Hexaholic

+0

'nVAlueString = "1,2,3"; 'nValueString.split("、 ");'を実行して、結果の配列を解析することができます。 – jrook

答えて

5

生プロパティファイルは、とにかく

そうです、あなたが代わりにJSONファイルを使用する必要があります:) 90`s

nValue=1,2,3 

が、その後nValueを読んで、スプリットコンマおよびストリーム/ループ構文解析にそれはintに

例:

String property = prop.getProperty("nValue"); 
System.out.println(property); 
String[] x = property.split(","); 
for (String string : x) { 
    System.out.println(Integer.parseInt(string)); 
} 
以降

のJava 8:は(","で)文字列のみsplit文字列として値(nValue=1,2,3)を読み取るには下記のようにして、次にint[]アレイへ変換する必要

int[] values = Stream.of(property.split(",")).mapToInt(Integer::parseInt).toArray(); 
for (int i : values) { 
    System.out.println(i); 
} 
+1

JSONが常にベストであるとは必ずしも同意できません。それはたいてい普通です。キーと値のペアリングは、その場所を持っています。 –

+0

こんにちは@JoPeyper、コメントありがとうございました...よくjsonは、xmlへの嫌な選択肢です...リストや配列が設定に含まれているときにこのような問題を引き起こします –

+1

はい、リストの場合は、JSON(およびXML)が優れていますプロパティよりも。私達は同意します! –

1

//split the input string 
String[] strValues=configuration.getProperty("nnValue").split(","); 
int[] intValues = strValues[strValues.length];//declare int array 
for(int i=0;i<strValues.length;i++) { 
    intValues[i] = Integer.parseInt(strValues[i]);//populate int array 
} 

今度はintValues配列を次のように渡してメソッドを呼び出すことができます。

ここで
-2

はJavaでプロパティファイルのプロパティを読み取る方法です:

Properties prop = new Properties(); 
try { 
    //load a properties file from class path, inside static method 
    prop.load(App.class.getClassLoader().getResourceAsStream("config.properties")); 

    //get the property value and print it out 
    System.out.println(prop.getProperty("database")); 
    System.out.println(prop.getProperty("dbuser")); 
    System.out.println(prop.getProperty("dbpassword")); 

} 
catch (IOException ex) { 
    ex.printStackTrace(); 
} 
+1

私はこれが実際に問題に対処しているとは思わない。 –

4

使用String.splitInteger.parseInt。ストリームを使用すると、1行でそれを行うことができます:あなたが春を使用している場合

String property = configuration.getProperty("nnValue") 
int[] values = Stream.of(property.split(",")).mapToInt(Integer::parseInt).toArray() 
1

は、あなたが直接あなたの特性にアレイ(しかし、あなたは、より複雑なデータを必要とする場合にも、マップする)読むことができます。例えば。

nValue={1,2,3} 

し、あなたのコード内で:application.propertiesにあなたがしたい場所

@Value("#{${nValue}}") 
Integer[] nValue; 

あなたはnValueを使用することができます。

関連する問題