[英]Java & Mac - How to write a file to relative path
我在带有将文件写入 Documents 文件夹的脚本的 Mac 上。 但是我希望能够将它写在可以发送给我的朋友的地方,而他们不必更改文件的路径。
File myFile = new File("Users/MyName/Documents/Test/user.text/");
有没有一种方法可以使我不必将MyName
切换到下一个人 PC 的名称?
系统属性“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!");
对于使用("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();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.