[英]How do I provide a file path in Mac OS X while creating a file in Java?
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.执行时,将在Temp
文件夹中创建一个名为“Example.txt”的新文件。 How do I provide the file path in Mac OS X?如何在 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.但这对我不起作用。
Forward slash "/" must be used to get the file path here. 必须使用正斜杠“/”来获取文件路径。 Use: 使用:
File f = new File("/Users/pavankumar/Desktop/Testing/Java.txt");
f.createNewFile();
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) 可以使用它们中的任何一个(第二个选项需要库)
有一个与File.separator
系统相关的常量,您应该使用它来为Java代码提供一些可移植性。
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
。
在 Mac OS 中这是以下面的方式工作,请尝试使用 File f = new File("/Users/bsingh/Desktop/Write/myTextFile.txt");
对于来自用户目录的 macos 中的相对文件路径,您可以使用 $Home。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.