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

时间:2017-12-22 18:22:42

标签: java

我正在制作一个打开并读取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);

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

ImageLoader从类路径加载资源,而LoadMap从文件系统加载它们,因此产生差异。

更具体地说,这会从InputStream类的类路径返回path对应路径ImageLoader的文件:

ImageLoader.class.getResource(path)

以下内容创建了一个从{em>文件系统中读取文件的Reader

new FileReader(path)

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