简体   繁体   中英

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(path);

            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 !!

        } 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")
    );

..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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM