如何在运行时从jar复制文件?

时间:2017-09-15 05:38:30

标签: java jar runtime

我想将我的项目中的src文件中的文件复制到我的目录,但是当我导出到runnable 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();
        } 

1 个答案:

答案 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);
}