从jar&获取txt stucked [英] Getting txt from jar & stucked

查看:133
本文介绍了从jar&获取txt stucked的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前开始编写一个可以加载不同游戏的棋盘游戏场。我将这些游戏存储在名为config.txt的文件中,但是我无法访问它。首先,我从我最喜欢的文件方法开始:

I currently started programming a board game playground which can load different games. I store these games in file named config.txt, but I am having trouble accessing it. Firstly, I started with my favourite file approach:

String fileAddress = "./resources/config.txt";
fis = new FileInputStream(fileAddress);
reader = new BufferedReader(new InputStreamReader(fis));

但是当我构建.jar文件时,它停止了工作。原因很明显。所以我发现自己环顾四周,发现了使用getResourceAsStream(String s)方法的建议。所以我将代码更改为以下方式:

But then when I built .jar file, it stopped working. For obvious reasons. So I found myself looking around and I found about recommendation to use getResourceAsStream(String s) method. So I changed my code to following way:

String fileAddress = "./resources/config.txt";
InputStream toReturn=null;
toReturn = this.getClass().getClassLoader().getResourceAsStream(fileAddress);

但在这里我陷入困境。无论我如何调整fileAddress(尝试./config.txt ./resources/config.txt ./resources/boardgames/config.txt和./resources/boardgames/config.txt)以及使用或省略getClassLoader(), toReturn的结果总是等于NULL并最终很快抛出NullPointerException。

But here I got stuck. No matter how I tweak the fileAddress (tried ./config.txt ./resources/config.txt ./resources/boardgames/config.txt and ./resources/boardgames/config.txt) and both using or omitting getClassLoader(), the result of toReturn just always equals NULL and ends up throwing NullPointerException very soon.

所需文件的位置如下。由于我没有足够的声誉,我将不得不将ASCII艺术作为文件层次结构。 config.txt都是有效目标。

Location of required file follows. As I do not have enough reputation, I will have to ASCII art the file hierarchy. Both config.txt are valid targets.

文件系统:

Boardgames
   src
   cache
   classes
   resources
      boardgames
         config.txt
      imgs
      config.txt

Jar文件内

BoardGames.jar
    boardgames
       <class files>
       config.txt
    imgs
    META-INF
    config.txt

因此,我需要帮助修复代码,以便正确读取文件。如果您可以提供如何从位于子文件夹imgs中的.png文件中获取ImageIcon的提示,因为我认为一旦通过config.txt超过初始化阶段,我将遇到类似的问题。

Therefore I would need an assistance with repairing the code so that it would read the file properly. If you could include tips how to get ImageIcon from the .png files located in subfolders imgs, since I reckon I will run into similar problem once I get past the initialization phase via config.txt.

感谢您的帮助。

推荐答案

感谢@EJP和@immibis提供的所有帮助。

thanks to @EJP and @immibis for all help.

this.getClass().getResourceAsStream("boardgames/config.txt");

最终让我运行的解决方案

was the solution that finally got me running

这篇关于从jar&amp;获取txt stucked的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆