在 Java 中创建文件时,如何在 Mac OS X 中提供文件路径?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30120813/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I provide a file path in Mac OS X while creating a file in Java?
提问by Pavan Kumar
File f = new File("C:\Temp\Example.txt");
f.createNewFile();
On executing, a new file named "Example.txt" will be created in the Temp
folder. How do I provide the file path in Mac OS X?
执行时,将在Temp
文件夹中创建一个名为“Example.txt”的新文件。如何在 Mac OS X 中提供文件路径?
I tried providing:
我尝试提供:
File f = new File("\Users\pavankumar\Desktop\Testing\Java.txt");
f.createNewFile();
But it didn't work for me.
但它对我不起作用。
采纳答案by Akash Rajbanshi
Forward slash "/" must be used to get the file path here. Use:
必须使用正斜杠“/”来获取此处的文件路径。用:
File f = new File("/Users/pavankumar/Desktop/Testing/Java.txt");
f.createNewFile();
回答by Jean-Baptiste Yunès
There is a File.separator
system-dependent constant that you should use to provide some portability to your Java code.
File.separator
您应该使用一个依赖于系统的常量来为 Java 代码提供一些可移植性。
回答by achedeuzot
On Linux, Mac OS X and other *nix flavours, the folder separator is /
not \
, so there isn't any need to escape anything, some/path/of/folders
.
在 Linux、Mac OS X 和其他 *nix 版本上,文件夹分隔符/
不是\
,因此无需转义任何内容some/path/of/folders
.
Also, you can use the /tmp
folder for your temporary files.
此外,您可以将该/tmp
文件夹用于临时文件。
Finally, on *nix systems, the home directory is usually represented by ~
or is in the environment variable HOME
.
最后,在 *nix 系统上,主目录通常由~
或 在环境变量中表示HOME
。
回答by Spindizzy
Please use File.separator to be independent from the OS:
请使用 File.separator 独立于操作系统:
String home = System.getProperty("user.home");
File f = new File(home + File.separator + "Desktop" + File.separator + "Testing" + File.separator + "Java.txt");
Or use org.apache.commons.io.FilenameUtils.normalize:
或者使用 org.apache.commons.io.FilenameUtils.normalize:
File f = new File(FileNameUtils.normalize(home + "/Desktop/Testing/Java.txt"));
Either of them can be used (the second option needs library)
它们中的任何一个都可以使用(第二个选项需要库)