【问题标题】:How can i load a file for multiple methods to access?如何加载文件以供多种方法访问?
【发布时间】:2020-03-21 20:43:00
【问题描述】:

我想在界面中加载和读取文本文件。我可以在列表中的一种方法中加载它:

 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;

    }

但我想在我的界面中的其他方法(如nextItem()boolean hasMoreItems())中使用此结果(列表)。 如何加载我的文件以便其他方法可以看到它?

【问题讨论】:

    标签: java file io


    【解决方案1】:

    通过直接在 ArrayList 中调用 read 方法来解决这个问题:

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

    现在这个类中的其他方法可以访问这个ArrayList了!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      • 2012-06-10
      • 1970-01-01
      • 1970-01-01
      • 2012-09-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多