Gewure Gewure - 2 months ago 21
Java Question

loading ArrayList<String> from java properties file

I'm reading from a properties-file using this method:

public void loadConfigFromFile(String path) {
Properties prop = new Properties();
InputStream input = null;

try {

//input = new FileInputStream("config.properties");
input = new FileInputStream(path);

// load a properties file
prop.load(input);

// .... saved like this:
// emails: abc@test.com, bbc@aab.com, .....
String wordsS = prop.getProperty("keywords");
String emailS = prop.getProperty("emails");
String feedS = prop.getProperty("feeds");

emails = Arrays.asList(emailS.split(",")); //ERROR !!
words = Arrays.asList( wordsS.split(","))); //ERROR !!
feeds = Arrays.asList( feedS.split(",")); //ERROR !!
allXHours = Float.valueOf(prop.getProperty("frequency"));

} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}


the fields to be written are declared as follows:

private ArrayList<String> emails = new ArrayList<>(
Arrays.asList("f00@b4r.com", "test@test.com")
);

private LinkedList<String> words = new LinkedList<>(
Arrays.asList("vuln", "banana", "pizza", "bonanza")
);

private LinkedList<String> feeds = new LinkedList<>(
Arrays.asList("http://www.kb.cert.org/vulfeed",
"https://ics-cert.us-cert.gov/advisories/advisories.xml",
"https://ics-cert.us-cert.gov/alerts/alerts.xml")
);


..so the compiler shows me the following Information, which I don't know how to use:


Incompatible types. Required
ArrayList<String>
but 'asList' was inferred to
List<T>
: no instance(s) of type variable(s) T exist so that
List<T>
conforms to
ArrayList<String>



How to circumvent this?

Answer Source

The problem is the type of the declared variable that you assign to emails = Arrays.asList(emailS.split(","));.
According to the compilation error, it is declared as ArrayList but Arrays.asList() returns a List.
You cannot assign a List to an ArrayList while you can do the reverse.

Besides Arrays.asList() return an instance of a private class : java.util.Arrays.ArrayList that is not the same that the ArrayList variable that you declare : java.util.ArrayList. So even a downcast to ArrayList would not work and cause a ClassCastException.

Change the declared variable from ArrayList<String> emails to List<String> emails and do the same thing for two other ArrayList variables.