我可以使用以下代码获取当前Java程序的工作目录:
Path path = Paths.get(*ClassName*.class.getProtectionDomain().getCodeSource().getLocation().toURI());
我还可以使用此命令获取运行 Java 进程的命令行参数(但输出中没有目录)wmic process get CommandLine where name='java.exe'/value
是否可以获取另一个 Java 进程的工作目录(更好地以编程方式)?也许可以通过一些 jdk/bin 实用程序来解决?
最佳答案
您可以通过 Attach API 获取此信息。要使用它,您必须将 jdk 的 tools.jar
添加到类路径中。然后,以下代码将打印所有已识别的 JVM 进程的当前工作目录:
for(VirtualMachineDescriptor d: VirtualMachine.list()) {
System.out.println(d.id()+"\t"+d.displayName());
try {
VirtualMachine vm = VirtualMachine.attach(d);
try(Closeable c = vm::detach) {
System.out.println("\tcurrent dir: "+vm.getSystemProperties().get("user.dir"));
}
}
catch(AttachNotSupportedException|IOException ex) {
System.out.println("\t"+ex);
}
}
关于java - 获取另一个Java进程的工作目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39516922/