简体   繁体   English

Java & Mac - 如何将文件写入相对路径

[英]Java & Mac - How to write a file to relative path

I'm on a mac with a script that's writing files to the Documents folder.我在带有将文件写入 Documents 文件夹的脚本的 Mac 上。 But I want to be able to write it where I can send it to my friends and they don't have to change the file's path.但是我希望能够将它写在可以发送给我的朋友的地方,而他们不必更改文件的路径。

File myFile = new File("Users/MyName/Documents/Test/user.text/");

Is there a way where I can make it relative where I don't have to switch around the MyName to whatever the next person PC's name is?有没有一种方法可以使我不必将MyName切换到下一个人 PC 的名称?

The system property 'user.home' is the magic you're looking for.系统属性“user.home”是您正在寻找的魔法。 Unfortunately, there is no OS-agnostic way to determine 'the documents' folder, probably because that is not a universal concept.不幸的是,没有与操作系统无关的方法来确定“文档”文件夹,可能是因为这不是一个通用概念。

You can always just do a quick check if it is there, and if so, use it.您总是可以快速检查它是否存在,如果存在,请使用它。 Also, there's a new file API, I suggest you use that.另外,还有一个新文件 API,我建议你使用它。

Putting it together:把它放在一起:

Path p = Paths.get(System.getProperty("user.home"));
Path candidate = p.resolve("Documents");
if (!Files.isDirectory(candidate)) candidate = p.resolve("My Documents");
if (!Files.isDirectory(candidate)) candidate = p;
p = p.resolve("Test").resolve("user.text");
Files.createDirectories(p.getParent());
Files.write(p, "Hello!");

For anyone who's having trouble with @rzwitserloot answer with the ("user.home") solution, Here's what works for me.对于使用("user.home")解决方案对@rzwitserloot 回答有问题的任何人,这对我有用。 It's a little messy but it's what works.这有点混乱,但它是有效的。

public class WritingFile {

    static String data = "This is THe DATA in the output file from a jar. Did it work!?!!";
    //static String paths;
    static String full;
    //static String tester = "/Users/226331/Documents/Test/filesname.txt/";
    public static void main(String[] args) {
        
        pathMaker();
        makeFile();
    }

    public static void pathMaker() {
        //Path path = new Paths.get("test.txt");
        String paths = System.getProperty("user.home");
        System.out.println(paths);
        //System.getenv(paths);
        //System.out.println(paths);
        
        full = paths + "/Documents/Test/filesname.txt/";
        System.out.println(full);
    }
    public static void makeFile() {
        try {
              // Creates a FileWriter
                File myFile = new File(full);
            FileWriter output = new FileWriter(myFile);

              // Writes the string to the file
              output.write(data);

              // Closes the writer
              output.close();
            }

            catch (Exception e) {
              e.getStackTrace();
              e.printStackTrace();
            }
    }
    
}

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

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