访问可执行jar中的文件和文件夹 [英] access files and folders in executable jars

查看:152
本文介绍了访问可执行jar中的文件和文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我面临以下问题: 我将Eclipse用于Java项目,并且具有以下结构:

I am facing the following problem: I use Eclipse for my Java projects and there I have the following structure:

  --> src
      --> package1
          ....
      --> package2
          ...

   -->dataFolder
       --> Folder1
            --> file1.xml
       --> Folder2
            file2.xml

在我的Java项目中,我解析了dataFolder目录中的所有文件.这没问题,因为我可以只使用eclipse项目的根目录,如下所示:

In my java project I parse all files in the dataFolder directory. This is no problem because I can just use the root directory of the eclipse project, like this:

File dataStoreFolder = new File("dataFolder");
Some parsing......

但是当我将项目导出为可执行jar文件时,我将无法再访问这些文件.当然,那是因为它们不在我放置exec.jar文件的文件夹中.但是我不想将整个文件夹和数据复制到我的exec.jar文件中.我可以以某种方式将其放在jar文件中吗? (我是通过将dataFolder添加到Java Build Path来实现的,但是它仍然无法像在Eclipse中那样工作)

But when I export my project as an executable jar file, I can not access these files anymore. Of course thats because they are not in the same folder where I put my exec.jar file. But I do not want to copy the whole folder with the data to my exec.jar file. Can I put it somehow inside my jar file? (I did it by adding the dataFolder to the Java Build Path but it still does not work as it does in Eclipse)

有人可以帮我吗?

推荐答案

使用jar文件时,这些文件不再作为文件存在.

When you're using a jar file, those files don't exist as files any more.

您可以将数据绝对包含在jar文件中,但是随后您还需要更改访问数据的代码.除了创建File对象外,您还需要类似以下内容:

You can absolutely include the data in your jar file, but then you'll need to change the code which accesses it, too. Instead of creating a File object, you'll need something like:

InputStream input = Foo.class.getResourceAsStream("/dataFolder/Folder1/file.xml");

因此,您有两个可分离的任务:

So you have two separable tasks:

  • 弄清楚如何在jar文件中包含数据文件夹
  • 更改代码以适当地访问数据

这篇关于访问可执行jar中的文件和文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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