[英]How to add class files and folders to a jar file from a directory in Java
[英]java: add a file to a jar directory
我正在研究一個項目,該項目要求用戶上載Java文件,該文件以后可以編譯成類文件。 我已經編寫了將文件上傳到項目文件夾的代碼。 使用Eclipse啟動時,它可以完美運行。 當我將項目打包為JAR時,就會出現問題。 該代碼引發異常。 我了解原因。.當我們打包項目時,僅將類文件加載到JAR中,而不是源文件中,並且JAR文件的位置也有所不同。
讓我解釋一下我已經做過的事情以及我需要做的事情:
在該項目的IDE版本中,我有類似以下內容:
用戶可以在其中瀏覽文件,然后單擊上載按鈕將其添加到項目結構中。 這與以下代碼完美配合:
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錯誤= 2,系統找不到在java.lang.ProcessBuilder.start中指定的文件(未知源)
有什么方法可以將文件上傳到JAR文件中的目錄?
String cmd = "jar uvf " + <jar file name> + " " + <name of file to be added;
System.out.println(cmd);
Process p = Runtime.getRuntime().exec(cmd);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.