如何解决系统找不到指定的文件错误?
how to resolve The system cannot find the file specified error?
对于一个项目,我需要读取一个包含宠物小精灵数据的 csv 文件,我尝试创建一个方法,允许我在我的 csv 文件中查找数据,如下所示:
private final String fileName = "./data/pokedex.csv";
String line = "";
private final String separator = ",";
private List<String> getPokeInfoById(int id) {
int i = 0;
List<String> info = null;
BufferedReader br;
try {
br = new BufferedReader(new FileReader(fileName));
while ((line = br.readLine()) != null) {
if (i == id) {
try (Stream<String> stream = Arrays.stream(line.split(","))) {
info = stream.collect(Collectors.toList());
}
} else {
i++;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return info;
}
但是 java 说:
java.io.FileNotFoundException: data\pokedex.csv (The system cannot find the file specified)
at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(FileInputStream.java:213)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:155)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:110)
[...]
这是我的 src 的样子:
C:.
├───controleur
├───data
│ grid_types.csv
│ moves.csv
│ pokedex.csv
│
├───img
├───model
│ │ Pokemon.java
│ │ Type.java
│ │
│ └───analyzer
│ Pokedex.java
│
└───test
PokedexTest.java
尝试在文件名中提供完整路径
所以我的路径似乎是错误的,因为我没有注意我当前目录使用的是什么
System.out.println(new File("."). getAbsolutePath());
帮助我找到了自己并找到了正确的道路
对于一个项目,我需要读取一个包含宠物小精灵数据的 csv 文件,我尝试创建一个方法,允许我在我的 csv 文件中查找数据,如下所示:
private final String fileName = "./data/pokedex.csv";
String line = "";
private final String separator = ",";
private List<String> getPokeInfoById(int id) {
int i = 0;
List<String> info = null;
BufferedReader br;
try {
br = new BufferedReader(new FileReader(fileName));
while ((line = br.readLine()) != null) {
if (i == id) {
try (Stream<String> stream = Arrays.stream(line.split(","))) {
info = stream.collect(Collectors.toList());
}
} else {
i++;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return info;
}
但是 java 说:
java.io.FileNotFoundException: data\pokedex.csv (The system cannot find the file specified)
at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(FileInputStream.java:213)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:155)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:110)
[...]
这是我的 src 的样子:
C:.
├───controleur
├───data
│ grid_types.csv
│ moves.csv
│ pokedex.csv
│
├───img
├───model
│ │ Pokemon.java
│ │ Type.java
│ │
│ └───analyzer
│ Pokedex.java
│
└───test
PokedexTest.java
尝试在文件名中提供完整路径
所以我的路径似乎是错误的,因为我没有注意我当前目录使用的是什么
System.out.println(new File("."). getAbsolutePath());
帮助我找到了自己并找到了正确的道路