问题
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
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......
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)
Can someone help me please?
回答1:
When you're using a jar file, those files don't exist as files any more.
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:
- Work out how to include the data folder within your jar file
- Change your code to access the data appropriately
回答2:
Yes, you can put them in your jar file. Just make dataFolder
a source folder under Eclipse, and it will copy the non-Java files to the target directory, and add them to the jar file.
Once in the jar file, you would get file1.xml
like this:
InputStream in = SomeClass.class.getResourceAsStream("/Folder1/file1.xml");
来源:https://stackoverflow.com/questions/11611704/access-files-and-folders-in-executable-jars