17
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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Pavan Kumar
  • 193
  • 2
  • 2
  • 7

4 Answers4

19

Forward slash "/" must be used to get the file path here. Use:

File f = new File("/Users/pavankumar/Desktop/Testing/Java.txt");
f.createNewFile();
Akash Rajbanshi
  • 1,515
  • 11
  • 22
17

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)

Louis Ferraiolo
  • 398
  • 3
  • 18
Spindizzy
  • 2,073
  • 15
  • 23
4

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.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
achedeuzot
  • 3,659
  • 4
  • 38
  • 48
3

There is a File.separator system-dependent constant that you should use to provide some portability to your Java code.

Jean-Baptiste Yunès
  • 30,872
  • 2
  • 40
  • 66