简体   繁体   English

如何使用相对路径而不是绝对路径?

[英]How to use relative path instead of absolute path?

So I am having a strange issue with Java. 所以我对Java有一个奇怪的问题。

I'm reading a writing files, so the path is important to me. 我正在读写文件,所以路径对我很重要。 I would like all files to be written and read from the relative path (ie in the folder with the rest of my class and java files). 我希望所有文件都是从相对路径写入和读取的(即在我的类和java文件的其余部分的文件夹中)。

I write files like so: 我写这样的文件:

FileWriter fw = new FileWriter(outfile,true);
fw.write(data);
fw.close();

where outfile is something like 'out.txt' (ie the name of the file we want the output to go in). outfile就像'out.txt'(即我们希望输出进入的文件的名称)。

The problem is, the file is created in /home/me/ instead of the path of my other files. 问题是,文件是在/home/me/创建的,而不是我的其他文件的路径。

Am i doing something wrong? 难道我做错了什么? Or how can i get the files stored in the relative directory? 或者我怎样才能将文件存储在相关目录中?

FileWriter fw = new FileWriter("./" + outfile,true);

or 要么

FileWriter fw = new FileWriter("~/" + outfile,true);

I would try that. 我会试试。

The working directory is where you run the program from ie where you call java YourClass, so when you want to write files relative to the class that's executing you'll have to know the current directory and append the relative path from there eg 工作目录是运行程序的地方,即你调用java YourClass的地方,所以当你想要编写相对于正在执行的类的文件时,你必须知道当前目录并从那里附加相对路径,例如

So if you have a class test.YourClass and you run the application from the source root ie 所以,如果你有一个类test.YourClass,你从源根运行应用程序,即

java test.YourClass java test.YourClass

you can find the absolute path to the directory your class file is in from the the user.dir system property and the classes package name as follows: 您可以从user.dir系统属性和类包名称中找到类文件所在目录的绝对路径,如下所示:

public class YourClass {

public void printPath() {
    String path = String.format("%s/%s", System.getProperty("user.dir"), this.getClass().getPackage().getName().replace(".", "/"));
    System.out.println(path);
}

} }

Java will save files relative to the current working directory. Java将保存相对于当前工作目录的文件。 Are you inside you home directory when you run the program? 当你运行程序时,你在你的主目录?

If you always want files to be saved relative to the location of the Java files and not the current working directory, you need to find that directory and prepend it to get an absolute path. 如果您总是希望相对于Java文件的位置而不是当前工作目录保存文件,则需要找到该目录并在其前面添加以获取绝对路径。

在命令行上设置user.dir属性,或者只是从你想要的所有目录运行(通过cd-ing)

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

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