[英]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.