How to use relative path instead of absolute path?

前端 未结 4 1462
说谎
说谎 2020-12-06 07:33

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 relati

相关标签:
4条回答
  • 2020-12-06 07:42
    FileWriter fw = new FileWriter("./" + outfile,true);
    

    or

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

    I would try that.

    0 讨论(0)
  • 2020-12-06 07:48

    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)

    0 讨论(0)
  • 2020-12-06 07:55

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

    }

    0 讨论(0)
  • 2020-12-06 07:56

    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.

    0 讨论(0)
提交回复
热议问题