我的Java程序如何在.jar文件中存储文件? [英] How can my Java program store files inside of its .jar file?

查看:128
本文介绍了我的Java程序如何在.jar文件中存储文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道.jar文件基本上都是归档文件和应用程序。我问的是如何在程序中存储数据(实际文件不仅仅是字符串)?我想在我的Java代码中执行此操作。

I know that .jar files are basically archives as well as being applications. What I'm asking is how can I store data(actual files not just strings) packed inside my program? I want to do this within my Java code.

如果您想知道我正在制作游戏的服务器模型,那么原因就在于此。服务器启动并创建所有级别数据,我想将所有这些文件存储在我的.jar应用程序中。

The reason for this if your wondering is that I'm producing a server mod of a game. The server starts and creates all the level data and I want to store all these file inside my .jar app.

推荐答案

是的你可以这样做。

类路径上的JAR文件中的非代码资源可以使用 Class.getResourceAsStream(String)进行访问。应用程序例行执行此操作,例如,将国际化消息作为资源包嵌入。

Non-code resources in a JAR file on the classpath can be access using Class.getResourceAsStream(String). Applications routinely do this, for example, to embed internationalized messages as resource bundles.

要将文件放入JAR文件,只需将其复制到输入中的适当位置即可运行 jar 命令之前的目录树。

To get your file into the JAR file, just copy it into the appropriate place in the input directory tree before you run the jar command.

关注

理论上,在某些情况下,您的应用程序可以将文件存储在自己的JAR文件中:

In theory, your application could store files inside its own JAR file, under certain circumstances:


  • JAR必须是本地文件系统中的文件;即不是从远程服务器获取的JAR。

  • 应用程序必须具有对JAR文件及其父目录的写访问权。

  • 应用程序不必读回它在当前类加载器中写入JAR的文件;即没有退出并重新启动。

  • JAR不需要签名。

  • The JAR has to be a file in the local file system; i.e. not a JAR that was fetched from a remote server.
  • The application has to have write access to the JAR file and its parent directory.
  • The application must not need to read back the file it wrote to the JAR in the current classloader; i.e. without exiting and restarting.
  • The JAR must not need to be be signed.

该程序将是:


  1. 找到JAR文件并以ZIP档案阅读器的形式打开。

  2. 创建ZIP存档编写器以编写新版本的JAR文件。

  3. 将应用程序的文件写入编写器。

  4. 从ZIP写入所有资源阅读器写入者,不包括旧版本的应用程序文件。

  5. 关闭阅读器和编写器。

  6. 重命名新版本的JAR以替换旧的。

  1. Locate the JAR file and open as a ZIP archive reader.
  2. Create a ZIP archive writer to write a new version of JAR file.
  3. Write the application's files to the writer.
  4. Write all resources from the ZIP reader to the writer, excluding old versions of the applications files.
  5. Close the reader and writer.
  6. Rename the new version of the JAR to replace the old one.

如果初始JAR被JVM / OS锁定,则最后一步可能不起作用。在这种情况下,您需要在包装器脚本中重命名。

The last step might not work if the initial JAR is locked by the JVM / OS. In that case, you need do the renaming in a wrapper script.

但是,我认为大多数人会同意这是一个不好的想法。只编写常规文件更简单,更健壮。

However, I think that most people would agree that this is a BAD IDEA. It is simpler and more robust to just write regular files.

这篇关于我的Java程序如何在.jar文件中存储文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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