2017-04-11 53 views
0

我有一个方法需要int[]作为输入。从java属性文件中读取一个int []

methodABC(int[] nValue) 

我想从Java属性文件

nValue=1,2,3 

如何从配置文件读取这个还是我来存储这些不同的格式借此n值?

我想什么是(changing the nValue to 123 instead of 1,2,3):

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

我们如何做到这一点?

+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

原始属性文件是如此90`s :)你应该使用一个JSON文件代替,

反正:

,如果你有这样的:

nValue=1,2,3 

然后读取n值,分裂以逗号和流/循环解析为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:

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

我不一定同意JSON总是最好的。它通常是。键/值配对虽然有其位置。 –

+0

嗨@JoPeyper,感谢您的评论...以及json是一个impoved替代xml ...当列表和数组出现在配置文件中时,它会杀死这样的问题 –

+1

是的,对于列表,JSON(和XML)更好比属性。我们同意! –

1

您需要读取的值(nValue=1,2,3)作为字符串仅split字符串(与","),然后转换为一个int[]阵列,如下所示:

//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阵列来调用该方法,如下所示:

methodABC(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。随着流,你可以做一个行:

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

如果你使用Spring,你可以阅读你的属性直接阵列(也地图,如果你需要更复杂的数据)。例如。在application.properties:

nValue={1,2,3} 

并在代码:

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

那么,你想,你可以使用n值。