gpt4 book ai didi

java - 系统找不到java中指定的txt文件

转载 作者:行者123 更新时间:2023-12-02 11:50:05 28 4
gpt4 key购买 nike

我正在制作一个打开和读取 png 和 txt 文件的程序。这是我的代码:

public static void init() {
//...
//compiler are finding a path for png files...
menu = ImageLoader.loadImage("/textures/menu.png");
options = ImageLoader.loadImage("/textures/options.png");
level = ImageLoader.loadImage("/textures/levelmenu.png");
levelOptions = ImageLoader.loadImage("/textures/leveloptions.png");

//..., but no for txt
map[0] = new LoadMap("/textures/lvl1.txt");
map[1] = new LoadMap("/textures/lvl2.txt");
map[2] = new LoadMap("/textures/lvl3.txt");
map[3] = new LoadMap("/textures/lvl4.txt");
map[4] = new LoadMap("/textures/lvl5.txt");
//...
}

但是当我运行它时,我收到此错误:

 \textures\lvl1.txt (The system cannot find the file specified)
\textures\lvl2.txt (The system cannot find the file specified)
\textures\lvl3.txt (The system cannot find the file specified)
\textures\lvl4.txt (The system cannot find the file specified)
\textures\lvl5.txt (The system cannot find the file specified)

我的文件 lvl1...5.txt 和 menu...levelOptions.png 位于同一目录

LoadMap 构造函数:

public LoadMap(String path) {
try {
BufferedReader reader = new BufferedReader(new FileReader(path));

String s = " ";
s = reader.readLine();
String[] wordsXY = s.split(" ");
x = wordsXY[0];
iX = Integer.parseInt(x);
y = wordsXY[1];
iY = Integer.parseInt(y);

while ((s = reader.readLine()) != null) {
String[] words = s.split(" ");
for (int i = 0; i < iY; i++) {
arrayList.add(Integer.parseInt(words[i]));
}
}
reader.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}

ImageLoader类:

public class ImageLoader {

public static BufferedImage loadImage(String path) {
try {
return ImageIO.read(ImageLoader.class.getResource(path));
} catch (IOException e) {
System.out.println(e.getMessage());
System.exit(1);
}
return null;
}
}

解决方案:

问题出在 loadMap 类中。

相反:

BufferedReader reader = new BufferedReader(new FileReader(path));

应该是:

InputStream is = getClass().getResourceAsStream(path);
InputStreamReader isr = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(isr);

感谢您的帮助。

最佳答案

ImageLoader 从类路径加载资源,而 LoadMap 从文件系统加载资源,因此结果不同。

更具体地说,这会返回一个 InputStream ,该文件对应于 ImageLoader 类的类路径中的路径 path 的文件:

ImageLoader.class.getResource(path)

下面创建了一个 Reader,它从文件系统中的文件中读取:

new FileReader(path)

您应该对这两种情况使用相同的机制以获得相同的结果。

关于java - 系统找不到java中指定的txt文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47945774/

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