在可运行的jar中加载和保存资源? [英] Loading and saving resources inside a runnable jar?

查看:171
本文介绍了在可运行的jar中加载和保存资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Java程序如何使用.jar中的文件进行读写?

我正在创建一个游戏,我希望所有的都可以从可运行的jar文件运行,所以所有我的资源(图像和文本文件)将在jar文件中。

I am in the process of creating a game, and I want it all to run from on runnable jar file, so all of my resources (images and text files) are going to be inside the jar file.

我遇到的问题是处理这个问题非常困难文件内的jar。

The problem that I'm having with this is that it is extremely difficult to deal with files inside the jar.

我正在使用eclipse,有时可以在你身上玩耍,因为如果你从eclipse运行它会找到文件,但如果你导出它不会。

I am using eclipse, which can sometimes play tricks on you because it will find the files if you run it from eclipse, but if you export it won't.

我只是想知道露出几件事情的正确方法:

I just want to know basically the proper way to dew a few things:


  1. 我需要加载图像(我有工作,不知何故,我修饰它,并做了发生事故,所以我不知道它是如何工作的)

  2. 我需要从文本文件中读取(我也是这样工作,再次,偶然和猜测的几个小时)。

  3. 我需要能够写入存储在jar中的文本文件。这是什么让我觉得我做错了。所有我想要做的是能够保存某些设置,以便下一次加载时工作,我不知道如何写入文件。

在eclipse(Indigo)中,我创建了一个名为资源的文件夹,并将其标记为源文件夹。我把所有的图像和文本文件放在那里。
我读这样的图像:

In eclipse (Indigo) I made a folder names "resources" and marked it as a source folder. I put all of my images and text files in there. I read in images like this:

public static Image ammo = new ImageIcon(TankMazeGame.class.getResource("ammo.png")).getImage();

我读这样的文本文件:

InputStream is = TankMazeRunner.class.getClassLoader().getResourceAsStream("Settings.txt");
Scanner settingsReader = new Scanner(new InputStreamReader(is));

我正在写给我的设置文件,但这不是真的有效,所以这就是我需要帮助。

I am writing to my settings file like this, but it isn't really working, so that's what I need help with.

File settingsFile = new File(DisplayMenu.class.getClassLoader().getResource("Settings.txt").getFile());
try {
    OutputStream os = new FileOutputStream(settingsFile, true);
    PrintWriter pw = new PrintWriter(os, true);
    pw.write("SIZE: " + TankMazeRunner.WIDTH + "\n");
    os.flush();
    pw.close(); 
} catch (Exception e2) {
    System.out.println("Error");
}

正如你可能从我的代码中可以看出,我迷路了。 p>

As you can probably tell from my code, I'm lost.

推荐答案


如何将设置写入JAR以外的知名位置?

How about you write settings to a well known location outside of the JAR?

作为保存设置的替代方法,请考虑以下方法之一:

As alternatives for saving settings, consider one of these approaches:


  • java.util.prefs.Preferences ,提到这里

JWS PersistenceService 描述这里

Cookie在 访问Cookie

Cookies, discussed in Accessing Cookies.

这篇关于在可运行的jar中加载和保存资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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