简体   繁体   中英

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. How do I provide the file path in 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:

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:

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 .

Also, you can use the /tmp folder for your temporary files.

Finally, on *nix systems, the home directory is usually represented by ~ or is in the environment variable HOME .

在 Mac OS 中这是以下面的方式工作,请尝试使用 File f = new File("/Users/bsingh/Desktop/Write/myTextFile.txt");

对于来自用户目录的 macos 中的相对文件路径,您可以使用 $Home。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM