How to use relative path instead of absolute path?

纵然是瞬间 提交于 2019-12-28 06:24:13

问题


So I am having a strange issue with 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 (i.e in the folder with the rest of my class and java files).

I write files like so:

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

where outfile is something like 'out.txt' (i.e. the name of the file we want the output to go in).

The problem is, the file is created in /home/me/ instead of the path of my other files.

Am i doing something wrong? Or how can i get the files stored in the relative directory?


回答1:


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

or

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

I would try that.




回答2:


The working directory is where you run the program from i.e. 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 e.g.

So if you have a class test.YourClass and you run the application from the source root i.e

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:

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);
}

}




回答3:


Java will save files relative to the current working directory. 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.




回答4:


set the user.dir property on the command line, or just run from the directory you wnt everything to be relative to (by cd-ing)



来源:https://stackoverflow.com/questions/4210239/how-to-use-relative-path-instead-of-absolute-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!