好吧,这可能与那里的几个问题非常相似,我一直在寻找,但无法解决这个问题。这是唯一阻止我的 .jar 正确编译的问题,所以我很想解决这个问题。
我有一个 highScores.dat 文件,我需要在 .jar 中读取和写入该文件,但我无法让输入和输出流接受路径,只能接受文件名,这对我来说没有意义。
这是我正在使用的方法:
public class HighScoreManager {
private File fileName = new File("highScores.dat");
public void addScore(String playerName, int score) {
loadScoreFile();
scores.add(new Score(playerName, score));
updateScoreFile();
}
public void loadScoreFile() {
try {
inputStream = new ObjectInputStream(new FileInputStream(fileName));
scores = (ArrayList<Score>) inputStream.readObject();
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
} catch (IOException e) {
System.out.println("IO Error: " + e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println("Class not found: " + e.getMessage());
} finally {
try {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
} catch (IOException e) {
System.out.println("IO Error: " + e.getMessage());
}
}
}
public void updateScoreFile() {
try {
outputStream = new ObjectOutputStream(new FileOutputStream(fileName));
outputStream.writeObject(scores);
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
} catch (IOException e) {
System.out.println("IO Error: " + e.getMessage());
} finally {
try {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
} catch (IOException e) {
System.out.println("Update Error: " + e.getMessage());
}}}}
路径是/highScores/highScores.dat ,它应该是正确的,因为位于/images/中的图像与 .jar 中的缓冲图像配合良好
编辑:将文件名更改为路径不起作用。我也尝试过 getClass().getResourceAsStream 无济于事。
最佳答案
您可以使用Class.getResourceAsStream
(或ClassLoader
)使用类或ClassLoader
来获取InputStream
“知道”该 jar 文件。
如果您发现 Class.getResourceAsStream()
不适合您,则您可能传入了错误的资源名称。即使在 Windows 上,它也区分大小写,并且相对于您调用它的类,除非您使用前导 /
。
但是,您不能以这种方式轻松写入到 jar 文件 - 您可以使用 JarOutputStream
构建一个完整的新 jar 文件,但我怀疑您不这样做我不想那样做。我个人会使用一个单独的文件 - 您始终可以查看该文件是否存在并从 jar 文件中读取。
关于java - 如何在 Jar 文件中读取/写入 .dat 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29974428/