如何让我的可视Java应用程序将自身复制到自定义目录?

时间:2016-05-07 17:47:03

标签: java jar copy

有人能给我一个用Java做的方法吗?

我知道步骤:

  1. 获取jar文件执行目录以获取.jar路径。
  2. 将.jar(使用获取的路径)复制到自定义目录。
  3. 我想要的是用于执行此操作的示例代码。关于#1步骤的其他帖子在某种程度上让我感到困惑,因为请参阅获取类目录,但我的目标是获取正在运行的.jar文件的完整且特定的路径以进行复制;并且还讨论了我不太了解的安全问题。用于复制文件的Java中的metoth对我来说也不清楚。为此,我请求代码示例。

    此外,如果将.jar文件包装到.exe文件中,还是有办法完成所有这些过程吗?其他帖子中的一些评论说“几乎不可能”,但出于什么原因这是不可能的?而且,真的不可能吗?

1 个答案:

答案 0 :(得分:1)

请注意,重要的是,运行以下代码的类(代码中的YourMainClass引用)是从jar文件加载的,您要复制:

String jarFilePath = YourMainClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();

当您获得jar文件路径时,您可以copy it到目录:

import static java.nio.file.StandardCopyOption.*;

Files.copy(source, target, REPLACE_EXISTING);

<强>更新

要避免在评论中报告Illegal char <:> at index 2:问题而不是FileSystems.getDefault().getPath(),请使用java.io.File类通过Path方法获取toPath()对象。

我已更新代码,并将目标文件夹路径从代码移动到应用程序参数。

完整的代码如下:

import java.io.File;
import java.io.IOException;
import static java.nio.file.StandardCopyOption.*;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;

public class JarFileCopyTester {

    public static void main(String[] args) throws URISyntaxException, IOException {

        // checking for mandatory application argument
        if (args.length != 1) {
            System.out.println("Usage:\njava -jar JarFileCopyTester.jar <targetFolderPath>");
            System.exit(0);
        }

        // the destination folder path, without filename
        String destinationFolderPath = args[0];
        if (!destinationFolderPath.endsWith(File.separator)) {
            destinationFolderPath = destinationFolderPath + File.separator;
        }

        // getting the running jar file path    
        String jarFilePath = JarFileCopyTester.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();

        // getting Path object related to the jarFilePath
        Path sourcePath = (new File(jarFilePath)).toPath();

        System.out.println("sourcePath: " + sourcePath);

        // getting jar file name only, to compose dest file path
        Path jarFileNameOnly = sourcePath.getFileName();

        // adding filename to the destination folder path
        String destinationFilePath = destinationFolderPath + jarFileNameOnly.toString();

        // composing the Path object for the destination file path
        Path destPath =(new File(destinationFilePath)).toPath();

        System.out.println("destination path: "  + destPath);

        // copying the file
        Files.copy(sourcePath, destPath, REPLACE_EXISTING);
    }
}

运行jar文件,调用命令:

视窗:

java -jar JarFileCopyTester.jar c:\myFolder1\myFolder2

Linux的:

java -jar JarFileCopyTester.jar /home/username/