繁体   English   中英

Java中的相对文件路径

[英]Relative file path in java

我有以下代码:

 Process p = Runtime.getRuntime().exec(command.toString(), null, 
                                          new File("D:\\Cognity"));

但是问题是Cognity目录并不总是在D:\\中,它可能在C:\\等中。所以我的问题是是否有办法给它一个相对路径,所以我不必更改此代码,具体取决于在使用该程序的PC上?

作为System.getProperty("user.dir")); 返回启动JVM的目录,您仍然不能保证您是在C:\\还是D:\\中。我的建议是将Cognity位置作为-D命令行参数传递并按如下方式使用:

Process p = Runtime.getRuntime().exec(command.toString(), null, new File(System.getProperty("cognity.dir")));

当然可以。

调用System.getProperty("user.dir")); 获取当前目录,并连接到结果的相对路径。

例如

String path=System.getProperty("user.dir"));
path+=realtivePath;

编辑:

Calrification:

例如:您要运行的程序始终位于向后两个文件夹,然后位于Temp dir。

因此,相对路径为..\\\\..\\Temp\\prog.exe.

假设在一台计算机上,您的程序位于C:\\ Users \\ user \\ Documents \\ Program,因此这是工作目录。

所以:

String path=System.getProperty("user.dir")); //returns the working directory
String realtivePath="\\ ..\\..\\Temp"; //no matter what is the first path, this is the relatuve location to the current dir
path+=realtivePath;
//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));

您可以使用config-File来设置绝对路径,也可以在jar文件的相对路径中创建该目录。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM