2

I have a class of which I need a different instance if one of its attributes changes. These changes are read at runtime from a property file. I would like to have a single file detailing the properties of all the single instances:

------------
name=Milan
surface=....
------------
name=Naples
surface=....

How can I load each set of properties in a different Property class (maybe creating a Properties[])? Is there a Java built in method to do so? Should I manually parse it, how could create an InputStream anytime I find the division String among the sets?

ArrayList<Properties> properties = new ArrayList<>();
if( whateverItIs.nextLine() == "----" ){
        InputStream limitedInputStream = next-5-lines ;
        properties.add(new Properties().load(limitedInputStream));
}

Something like above. And, by the way, any constructor method which directly creates the class from a file?

EDIT: any pointing in the right direction to look it for myself would be fine too.

Bilesh Ganguly
  • 3,792
  • 3
  • 36
  • 58
Vale
  • 1,104
  • 1
  • 10
  • 29

1 Answers1

2

First of all, read the whole file as a single string. Then use split and StringReader.

String propertiesFile = FileUtils.readFileToString(file, "utf-8");
String[] propertyDivs = propertiesFile.split("----");
ArrayList<Properties> properties = new ArrayList<Properties>();

for (String propertyDiv : propertyDivs) {
     properties.add(new Properties().load(new StringReader(propertyDiv)));
}

The example above uses apache commons-io library for file to String one-liner, because Java does not have such a built-in method. However, reading file can be easily implemented using standard Java libraries, see Whole text file to a String in Java

Community
  • 1
  • 1
vojta
  • 5,591
  • 2
  • 24
  • 64
  • I use to access my file getting the resource. Is this the right approach: `File f = new File(this.getClass().getClassLoader().getResource("cities.prop").getPath());` – Vale May 25 '16 at 09:33
  • @Vale It is OK in my opinion. See this: http://stackoverflow.com/a/1318386/3899583 – vojta May 25 '16 at 09:47