我有这段代码:
Process p = Runtime.getRuntime().exec(command.toString(), null,
new File("D:\\Cognity"));
但问题是Cognity目录并不总是在D:\中,它也可能在C:\等其他位置。因此我的问题是是否有一种方式可以给它一个相对路径,这样我就不需要根据使用程序的计算机来更改代码了?
我有这段代码:
Process p = Runtime.getRuntime().exec(command.toString(), null,
new File("D:\\Cognity"));
但问题是Cognity目录并不总是在D:\中,它也可能在C:\等其他位置。因此我的问题是是否有一种方式可以给它一个相对路径,这样我就不需要根据使用程序的计算机来更改代码了?
调用 System.getProperty("user.dir");
来获取当前目录,然后将相对路径与结果连接。
例如:
String path = System.getProperty("user.dir");
path += relativePath;
编辑:
澄清:
例如: 您要运行的程序始终位于向后两个文件夹的位置,然后位于Temp目录。
因此,相对路径为 ..\\..\\Temp\\prog.exe。
假设在一台计算机上,您的程序位于C:\\Users\\user\\Documents\\Program
,因此这是工作目录。
所以:
String path = System.getProperty("user.dir"); //returns the working directory
String relativePath = "\\ ..\\..\\Temp"; //no matter what is the first path, this is the relative location to the current dir
path += relativePath;
//in this example, path now equals C:\Users\user\Documents\Program\..\..\Temp\prog.exe = C:\Users\user\Temp\prog.exe
Process p = Runtime.getRuntime().exec(command.toString(), null, new File(path));
由于System.getProperty("user.dir"));
返回的是启动JVM的目录,因此您仍无法保证您在C:\还是D:\。我的建议是将Cognity位置作为-D命令行参数传递,并像这样使用:
Process p = Runtime.getRuntime().exec(command.toString(), null, new File(System.getProperty("cognity.dir")));