How do I move a file into a compiled .jar file using Java?

放肆的年华 提交于 2021-02-08 12:07:58

问题


I'm making a file import system, and I can't move files into the compiled .jar file the application is in. Here's what I'm trying to do:

Path FROM = Paths.get(filePath.getText());
Path TO = Paths.get("C:\\Users\\" + System.getProperty("user.name") + 
"\\AppData\\Roaming\\.minecraft\\mods\\music_crafter-1.0\\src\\main\\resources\\assets\\music_crafter\\sounds\\block\\music_player");
                                       //jar file
Files.move(FROM, TO.resolve(FROM.getFileName()), StandardCopyOption.REPLACE_EXISTING);

回答1:


You need to handle the jar file internally. A Jar is not a directory, it is a compressed container file (pretty much a ZIP file with a different extension).

To do this, given that you are on Java 6, you have 2 options:

  1. Unzip the contents to a temporary working directory (there are built in APIs for this, or use a library such as Apache Commons Compress) do your work (copying, deleting, etc) and then re-zip.
  2. Make external command line calls to the Jar utilities that come with Java

Of those, only (1) makes any real sense.

A third option would be available if you could up your Java to 7+ which would be: 3. Use a Zip File System Provider to to treat it as a file system in code

All that said, however:

As per comments on your question, you really might want to look at if this something you need to do at all? Why do you need to insert into existing jars? If this is 'external' data, it would be much better in a separate resource location/container, not the application jar.



来源:https://stackoverflow.com/questions/43090103/how-do-i-move-a-file-into-a-compiled-jar-file-using-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!