File f = new File("C:\\Temp\\Example.txt");
f.createNewFile();
执行后,将在 Temp
文件夹中创建一个名为 "Example.txt" 的新文件。我该如何在Mac OS X中提供文件路径?
我尝试提供:
File f = new File("\\Users\\pavankumar\\Desktop\\Testing\\Java.txt");
f.createNewFile();
但是对我来说没有起作用。
File f = new File("C:\\Temp\\Example.txt");
f.createNewFile();
执行后,将在 Temp
文件夹中创建一个名为 "Example.txt" 的新文件。我该如何在Mac OS X中提供文件路径?
我尝试提供:
File f = new File("\\Users\\pavankumar\\Desktop\\Testing\\Java.txt");
f.createNewFile();
但是对我来说没有起作用。
在这里必须使用斜杠"/"来获取文件路径。使用:
File f = new File("/Users/pavankumar/Desktop/Testing/Java.txt");
f.createNewFile();
请使用Java内置的File.separator
来实现与操作系统无关,像这样:
String home = System.getProperty("user.home");
File f = new File(home + File.separator + "Desktop" + File.separator + "Testing" + File.separator + "Java.txt");
或者使用静态实用方法 FilenameUtils.normalize
(来自库和包org.apache.commons.io
):
File f = new File(FileNameUtils.normalize(home + "/Desktop/Testing/Java.txt"));
两者都可以使用;第二个选项需要外部库Apache Commons IO。
FilenameUtils.normalize(String filename)
。 - Harshit/
而不是\
,所以没有必要转义任何内容,some/path/of/folders
。/tmp
文件夹来存储临时文件。~
表示或在环境变量HOME
中。在Java代码中,有一个系统相关的常量File.separator
,你应该使用它来提高你的代码可移植性。