java:将文件添加到jar目录

时间:2017-07-07 12:36:54

标签: java eclipse maven jar processbuilder

我正在开发一个项目,要求用户上传一个Java文件,以后可以将其编译成一个类文件。我已经编写了将文件上传到项目文件夹的代码。使用Eclipse启动时它非常有效。当我将项目打包为JAR时会出现问题。代码抛出异常。我理解原因..当我们打包项目时,只有类文件被加载到JAR而不是源文件中,并且JAR文件的位置也有所不同。

让我解释一下我做了什么以及我需要做什么:

在项目的IDE版本中,我有类似的东西: enter image description here
用户可以浏览文件并单击上传按钮将其添加到项目结构中。这与以下代码完美配合:

String path = Paths.get(".").toAbsolutePath().normalize().toString()+"\\path\\to\\directory";
File source=new File(textField1.getText());
String fileName="";
try {
    fileName=new java.io.File(textField1.getText()).getName();
    Files.copy(source.toPath(),new java.io.File(path+fileName).toPath(),REPLACE_EXISTING);
} catch (IOException e2) {
    e2.printStackTrace();
}

当我必须使用JAR文件运行相同的代码时,我理解我应该更改如何获取项目的根目录,然后导航到所需的目录。不知何故,我无法让它发挥作用。我已经尝试了以下内容:

URL location=MainClass.class.getProtectionDomain().getCodeSource().getLocation();
String p = URLDecoder.decode(location.getFile(), "UTF-8");
System.out.println(location);

这会打印rsrc:./。如何将上传的文件复制到Jar文件中的所需目录?

我还尝试了另一种方法,我想创建一个shell脚本来执行jar uf jar-file input-file(s)。我将JAR文件和此shell脚本放在同一目录中,并执行以下代码:

try {
        String fileName = "shellFile.sh";
        URL location=MainClass.class.getProtectionDomain().getCodeSource().getLocation();
        String p = URLDecoder.decode(location.getFile(), "UTF-8");
        System.out.println(location);
        String inputFilePath = p + fileName;
        System.out.println(inputFilePath);
        Process process = Runtime.getRuntime().exec(inputFilePath);
    } catch (IOException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    }

但我得到以下例外:

  

java.io.IOException:无法运行程序“./shellFile.sh”:CreateProcess error = 2,系统找不到指定的文件           在java.lang.ProcessBuilder.start(未知来源)

有什么办法可以将文件上传到JAR文件中的目录吗?

1 个答案:

答案 0 :(得分:0)

String cmd = "jar uvf " + <jar file name> + " " + <name of file to be added;
System.out.println(cmd);
Process p = Runtime.getRuntime().exec(cmd);
相关问题