java - 尝试读取文本文件时出现 IO 异常错误

标签 java android

我正在尝试读取一个文本文件,其中包含机场信息的字符串(以逗号分隔)。但是,当我尝试读取该文件时,它会抛出 IOException。这是代码:

public ArrayList<ArrayList<String>> createAirportLibrary() {

    ArrayList<ArrayList<String>> airportLibrary = new ArrayList<>();
    String[] line;
    BufferedReader reader = null;

    try {

        // import the text file
        File airportsFile = new File("C:\\Users\\cjkei\\AndroidStudioProjects\\TravelTime\\app\\libs\\airports.txt");

        // read the first line of the file
        reader = new BufferedReader(new FileReader(airportsFile));
        line = reader.readLine().split(",");

        // loop through each line of file and add each airport to the library
        while (line != null) {
            int i = 0;
            ArrayList<String> thisAirport = new ArrayList<>();
            while (i < line.length){
                if (line[i] instanceof String){
                    thisAirport.add(line[i]);
                }
                else {
                    airportLibrary.add(thisAirport);
                    thisAirport.clear();
                }
                i++;
            }
            line = reader.readLine().split(",");
        }
    }
    catch (IOException e) {
        Context context = this;
        String text = "error reading file";
        int duration = Toast.LENGTH_SHORT;
        Toast.makeText(context, text, duration).show();
    }
    finally {
        try {
            if (reader != null) {
                reader.close();
            }
        }
        catch (IOException e) {
            Context context = this;
            String text = "could not close reader";
            int duration = Toast.LENGTH_SHORT;
            Toast.makeText(context, text, duration).show();
        }
    }
    return airportLibrary;
}

我尝试一步步调试,但是在 onCreate 调用之后,它显示 this .

最佳答案

您可能想尝试一下函数 Files.lines 。它返回 Stream<String>然后您可以迭代该流。

Stream<String> stream = Files.lines(Paths.get(fileName))
stream.forEach(this::doSomethingWithLine);

private void doSomethingWithLine(String line) {
  // actually do something
}

关于java - 尝试读取文本文件时出现 IO 异常错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57331297/

相关文章:

java - 在 Spring Data JPA 存储库中使用 EntityGraph 进行过滤

java - "INSTALL_PARSE_FAILED_MANIFEST_MALFORMED"在Android Studio中运行项目时出错

java - 如何动态设置SQL准备语句的参数

java - 如何使用 println 按单位打印同一列中的数字列表?

JavaFX - 在 Controller 类之间传递 int 值会产生不正确的结果

android - 是否有唯一的 Android 设备 ID?

android - 可检查的 ImageView

android - this.Touch - 多次触发事件,不知道如何取消订阅

android - 在Interceptor中抛出IOException会导致Retrofit崩溃

android - 为基于 IOS 和 Android 的设备编写一个客户端