Pulling values from a Java Properties file in order?

前端 未结 15 761
庸人自扰
庸人自扰 2020-12-02 18:32

I have a properties file where the order of the values is important. I want to be able to iterate through the properties file and output the values based on the order of the

15条回答
  •  误落风尘
    2020-12-02 19:19

    In some answers it is assumed that properties read from file are put to instance of Properties (by calls to put) in order they appear they in file. While this is in general how it behaves I don't see any guarantee for such order.

    IMHO: it is better to read the file line by line (so that the order is guaranteed), than use the Properties class just as a parser of single property line and finally store it in some ordered Collection like LinkedHashMap.

    This can be achieved like this:

    private LinkedHashMap readPropertiesInOrderFrom(InputStream propertiesFileInputStream)
                                                               throws IOException {
        if (propertiesFileInputStream == null) {
          return new LinkedHashMap(0);
        }
    
        LinkedHashMap orderedProperties = new LinkedHashMap();
    
        final Properties properties = new Properties(); // use only as a parser
        final BufferedReader reader = new BufferedReader(new InputStreamReader(propertiesFileInputStream));
    
        String rawLine = reader.readLine();
    
        while (rawLine != null) {
          final ByteArrayInputStream lineStream = new ByteArrayInputStream(rawLine.getBytes("ISO-8859-1"));
          properties.load(lineStream); // load only one line, so there is no problem with mixing the order in which "put" method is called
    
    
          final Enumeration propertyNames = properties.propertyNames();
    
          if (propertyNames.hasMoreElements()) { // need to check because there can be empty or not parsable line for example
    
            final String parsedKey = (String) propertyNames.nextElement();
            final String parsedValue = properties.getProperty(parsedKey);
    
            orderedProperties.put(parsedKey, parsedValue);
            properties.clear(); // make sure next iteration of while loop does not access current property
          }
    
          rawLine = reader.readLine();
        }
    
        return orderedProperties;
    
      }
    

    Just note that the method posted above takes an InputStream which should be closed afterwards (of course there is no problem to rewrite it to take just a file as an argument).

提交回复
热议问题