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

查看:29
本文介绍了我的 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 必须不需要签名.

程序是:

  1. 找到 JAR 文件并作为 ZIP 存档阅读器打开.
  2. 创建一个 ZIP 存档编写器来编写新版本的 JAR 文件.
  3. 将应用程序的文件写入编写器.
  4. 将 ZIP 读取器中的所有资源写入写入器,不包括旧版本的应用程序文件.
  5. 关闭读取器和写入器.
  6. 重命名新版本的 JAR 以替换旧版本.

如果初始 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天全站免登陆