【问题标题】:Java & Mac - How to write a file to relative pathJava & Mac - 如何将文件写入相对路径
【发布时间】:2020-11-24 02:14:53
【问题描述】:

我在 Mac 上使用脚本将文件写入 Documents 文件夹。但我希望能够将它写在我可以发送给我的朋友的地方,而他们不必更改文件的路径。

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

有没有一种方法可以让我不必将MyName 切换到下一个人电脑的名字?

【问题讨论】:

标签: java macos file path


【解决方案1】:

对于使用("user.home") 解决方案的@rzwitserloot 回答有问题的任何人,这对我有用。这有点乱,但它是有效的。

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

【讨论】:

    【解决方案2】:

    系统属性“user.home”是您正在寻找的魔法。不幸的是,没有与操作系统无关的方法来确定“文档”文件夹,可能是因为这不是一个通用概念。

    您总是可以快速检查它是否存在,如果存在,请使用它。另外,还有一个新的文件 API,我建议你使用它。

    把它放在一起:

    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!");
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-27
    • 1970-01-01
    • 1970-01-01
    • 2017-10-07
    • 2012-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多