gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 02:10:21 25 4
gpt4 key购买 nike

我正在尝试读取一个文本文件,其中包含机场信息的字符串(以逗号分隔)。但是,当我尝试读取该文件时,它会抛出 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com