How do I provide a file path in Mac OS X while creating a file in Java?

后端 未结 4 642
旧时难觅i
旧时难觅i 2021-02-04 04:28
File f = new File(\"C:\\\\Temp\\\\Example.txt\");
f.createNewFile();

On executing, a new file named \"Example.txt\" will be created in the Temp

4条回答
  •  攒了一身酷
    2021-02-04 05:01

    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)

提交回复
热议问题