文本文件:
Europe, France, Paris
Asia, China, Beijing
Africa, Congo
我正在尝试将此txt文件写入数组列表。我在第四行出现错误。
public class Address {
private String continent;
private String country;
private String city;
public Adresa(String continent, String country, String city) {
this.continent = continent;
this.country = country;
this.city = city;
}
private static List<Address> readAddressFromFile(String fileName) {
List<Address> addresses = new ArrayList<>();
Path pathToFile = Paths.get(fileName);
try (BufferedReader br = Files.newBufferedReader(pathToFile, StandardCharsets.UTF_8)) {
String line = br.readLine();
while (line.length() > 0) {
String[] attributes = line.split(", ");
Address address = createAddress(attributes);
addresses.add(address);
line = br.readLine();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return addresses;
}
private static Adresa createAddress(String[] metadata) {
String continent = metadata[0];
String country = metadata[1];
String city = metadata[2];
return new Address(continent, country, city);
}
我懂了
“ ArrayIndexOutOfBoundsException:2”
错误,因为我在第四行只有2个元素。我该如何解决?
最佳答案
我建议您在第三个元素上添加一个if
private static Adresa createAddress(String[] metadata) {
String continent = metadata[0];
String country = metadata[1];
String city = "";
if(metadata.length>2){
city = metadata[2];
}
return new Address(continent, country, city);
}
关于java - 将文本文件写入数组列表-ArrayIndexOutOfBoundsException错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57177172/