繁体   English   中英

如何在Jar文件中读取/写入.dat文件?

[英]How to read/write .dat file within Jar file?

好的,这可能与那里的一些问题非常相似,我一直在寻找,但无法解决此问题。 这是阻止我的.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 )使用一个“知道”该jar文件的类或ClassLoader来获得InputStream

如果发现Class.getResourceAsStream()对您不起作用,则可能是传递了错误的资源名称。 即使在Windows上,它也区分大小写,并且相对于您调用的类,除非您使用前导/

但是,您不能以这种方式轻松地写入 jar文件-您可以使用JarOutputStream构建一个完整的新jar文件,但我怀疑您不想这样做。 我个人将使用一个单独的文件-您始终可以查看该文件是否存在,否则可以从jar文件中读取。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM