简体   繁体   English

Java中的相对文件路径

[英]Relative file path in java

I have this code: 我有以下代码:

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

But the thing is the Cognity directory is not always in D:\\, it could be in C:\\ etc. So my question is if there is a way to give it a relative path so I don't have to change this code depending on the PC that uses the program? 但是问题是Cognity目录并不总是在D:\\中,它可能在C:\\等中。所以我的问题是是否有办法给它一个相对路径,所以我不必更改此代码,具体取决于在使用该程序的PC上?

As System.getProperty("user.dir")); 作为System.getProperty("user.dir")); returns the directory from which the JVM was launched you still can't guarantee whether you're in C:\\ or D:\\ My advice would be to pass the Cognity location in as a -D commandline argument and use it like this: 返回启动JVM的目录,您仍然不能保证您是在C:\\还是D:\\中。我的建议是将Cognity位置作为-D命令行参数传递并按如下方式使用:

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

Sure there is. 当然可以。

Call System.getProperty("user.dir")); 调用System.getProperty("user.dir")); to get your current dir, and concat the relative path to the result. 获取当前目录,并连接到结果的相对路径。

eg 例如

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

EDIT: 编辑:

Calrification: Calrification:

For example: The program you want to run is always located two folders backwards, and then at Temp dir. 例如:您要运行的程序始终位于向后两个文件夹,然后位于Temp dir。

So the relative path is ..\\\\..\\Temp\\prog.exe. 因此,相对路径为..\\\\..\\Temp\\prog.exe.

Let's say that in one computer you have your program located at C:\\Users\\user\\Documents\\Program, so this is the working directory. 假设在一台计算机上,您的程序位于C:\\ Users \\ user \\ Documents \\ Program,因此这是工作目录。

So: 所以:

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