18
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
  • 30,738
  • 21
  • 105
  • 131
Pavan Kumar
  • 203
  • 2
  • 3
  • 7

6 Answers6

23

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,553
  • 11
  • 23
22

Please use Java's built-in File.separator to be independent from the OS, like this:

String home = System.getProperty("user.home");
File f = new File(home + File.separator + "Desktop" + File.separator + "Testing" + File.separator + "Java.txt");

Or use the static utility-method FilenameUtils.normalize (from library and package org.apache.commons.io):

File f = new File(FileNameUtils.normalize(home + "/Desktop/Testing/Java.txt"));

Either of them can be used; the second option needs the external library Apache Commons IO.

hc_dev
  • 8,389
  • 1
  • 26
  • 38
Spindizzy
  • 7,244
  • 1
  • 19
  • 33
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
  • 30,738
  • 21
  • 105
  • 131
achedeuzot
  • 4,164
  • 4
  • 41
  • 56
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
  • 34,548
  • 4
  • 48
  • 69
0

For the relative file path in macos from the Users directory you can use $Home.

TPT
  • 1
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 10 '22 at 22:29
-1

In Mac OS This is working in below fashion, please try with File f = new File("/Users/bsingh/Desktop/Write/myTextFile.txt");

  • 1
    This has already been mentioned in the other answers. *When answering older questions that already have answers, please make sure you provide either a novel solution or a significantly better explanation than existing answers.* – Eric Aya Nov 18 '21 at 11:29