有人可以给我一种在 Java 中执行此操作的方法吗?
我知道步骤:
- 获取jar文件执行目录,用于获取.jar路径。
- 将该 .jar(使用获取的路径)复制到自定义目录。
我想要的是执行此操作的示例代码。这里关于#1 步骤的其他帖子在某种程度上让我感到困惑,因为引用获取类目录,但我的目标是获取正在运行的 .jar 文件的完整且特定的路径以进行复制;还谈到了我不太了解的安全问题。另外,我不清楚 Java 中复制文件的方法。为此,我请求代码示例。
此外,如果 .jar 文件包装到 .exe 文件中,有办法完成所有这些过程吗?其他帖子中的一些评论说“几乎不可能”,但为什么不可能呢?而且,真的不可能吗?
最佳答案
请注意,重要的是,运行以下代码的类(代码中的 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 文件,请调用命令:
Windows:
java -jar JarFileCopyTester.jar c:\myFolder1\myFolder2
Linux:
java -jar JarFileCopyTester.jar /home/username/
关于java - 如何使我的可视化 Java 应用程序将自身复制到自定义目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37091802/