Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 651
Pavan Kumar Avatar asked May 08 '15 09:05

Pavan Kumar


People also ask

How do I enable file path on Mac?

Show the path to a file or folder On your Mac, click the Finder icon in the Dock to open a Finder window. Choose View > Show Path Bar, or press the Option key to show the path bar momentarily. The location and nested folders that contain your file or folder are displayed near the bottom of the Finder window.

What is the path of Java in Mac?

Note: In macOS, the JDK installation path is /Library/Java/JavaVirtualMachines/jdk-10. jdk/Contents/Home . /jdk-10.

How do I associate a file type with a program on a Mac?

Alternatively, right-click on the file and select Get Info. Click the down arrow for Open with, click the drop-down menu to choose the default app, and then click Change All to always associate that file type with your chosen app.


2 Answers

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

File f = new File("/Users/pavankumar/Desktop/Testing/Java.txt");
f.createNewFile();
like image 107
Akash Rajbanshi Avatar answered Sep 29 '22 11:09

Akash Rajbanshi


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)

like image 32
Spindizzy Avatar answered Sep 29 '22 09:09

Spindizzy