【问题标题】:Reading a int[] from java properties file从 java 属性文件中读取 int[]
【发布时间】:2017-09-06 09:15:45
【问题描述】:

我有一个将int[] 作为输入的方法。

methodABC(int[] nValue)

我想从 Java 属性文件中获取这个 nValue

nValue=1,2,3

如何从配置文件中读取它,还是必须以不同的格式存储它?

我尝试的是(changing the nValue to 123 instead of 1,2,3):

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

我们如何做到这一点?

【问题讨论】:

  • 不确定是否重复,但这可能对您来说很有趣:stackoverflow.com/questions/7015491/…
  • 如果nVAlueString="1,2,3"; 你可以这样做:nValueString.split(","); 然后解析结果数组。

标签: java arrays parsing properties-file


【解决方案1】:

原始属性文件是 90 年代的 :) 你应该使用 json 文件,

无论如何:

如果你有这个:

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 开始:

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

【讨论】:

  • 我不一定同意 JSON 总是最好的。它通常是。键/值对虽然有它的位置。
  • 嗨@JoPeyper,感谢您的评论......好吧,json 是 xml 的一种改进的替代品......当配置中存在列表和数组时,它可以解决这样的问题
  • 是的,对于列表,JSON(和 XML)比属性更好。我们同意!
【解决方案2】:

您需要仅将值(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);

【讨论】:

    【解决方案3】:

    这里是如何在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();
    }
    

    【讨论】:

    • 我不认为这实际上是在解决这个问题。
    【解决方案4】:

    使用String.splitInteger.parseInt。使用 Streams,您可以在一行中完成:

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

    【讨论】:

      【解决方案5】:

      如果您使用 Spring,您可以直接读取属性中的数组(如果您需要更复杂的数据,还可以读取映射)。例如。在 application.properties 中:

      nValue={1,2,3}
      

      在你的代码中:

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

      然后你可以在你想要的地方使用 nValue。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-12-23
        • 1970-01-01
        • 1970-01-01
        • 2012-01-07
        • 1970-01-01
        • 2012-01-21
        • 1970-01-01
        • 2013-10-25
        相关资源
        最近更新 更多