Search code examples
javafileio

How can i load a file for multiple methods to access?


I'd like to load and read a text file inside an interface. I can load it within one method inside a list:

 static List readFile(String fileName) throws IOException {
        List result;
        try (Stream<String> lines = Files.lines(Paths.get(fileName))) {
            result = (List) lines.collect(Collectors.toList());
        }
        return result;

    }

But I want to use this result (list) inside other methods I have in my interface like nextItem() and boolean hasMoreItems(). How can I load my file so that the other methods can see it?


Solution

  • Figured it out by calling the read method straight into the ArrayList:

    public final ArrayList<String> file = readLines(); // Stores read config file
    ListIterator<String> list = file.listIterator(); // Iterates through stored config file
    
    public ArrayList<String> readLines() { // Reads config file
    
        try {
            ArrayList<String> lines = new ArrayList<>(
                    Files.readAllLines(Paths.get("configFile.txt")));
    
            return lines;
        } catch (IOException e) {
            // handle exception
        }
        return null;
    }
    

    Now the other methods in this class can access this ArrayList!