2017-09-15 65 views
1

我想從我的項目中的src文件複製一個文件到我的目錄,但是當我導出到可運行jar時它不工作。如何在運行時從jar中複製文件?

 public static void main(String args[]) throws IOException{ 
     FileCopyController fpc = new FileCopyController(); 
     File fileSrc = new File("src/java.exe"); 
     File fileDest = new File("C:/Directory1/java.exe"); 
     fpc.copyFileUsingChannel(fileSrc, fileDest); 
    } 

    public void copyFileUsingChannel(File source, File dest) throws IOException { 
    InputStream is = null; 
     OutputStream os = null; 
     try { 
      is = new FileInputStream(source); 
      os = new FileOutputStream(dest); 
      byte[] buffer = new byte[1024]; 
      int length; 
      while ((length = is.read(buffer)) > 0) { 
       os.write(buffer, 0, length); 
      } 
     } finally { 
      is.close(); 
      os.close(); 
     } 
+0

JAR通常不包含源代碼。如果您的JAR包含所需的文件,您可以使用類加載程序爲您找到它,以便您可以打開/複製它.... –

+0

可以給我一個例子,謝謝 –

回答

2

嘗試是這樣的:

public static void main(String args[]) throws IOException 
{ 
    final InputStrean src = getClass().getResourceAsStream("/java.exe"); 
    final Path dest = new File("C:/Directory1/java.exe").toPath(); 
    Files.copy(src, dest, StandardCopyOption.REPLACE_EXISTING); 
} 
+0

它的作品!謝啦 –