简体   繁体   中英

Java file names that can work for both unix and windows

My need is to open a file (temp file) and write something to it How can I do it so that it would work for all the OS types (at least for unix and windows)

Below is my current code Every time, I want to test something on windows, I will be to toggle between these lines (comment/uncomment)

//File file = new File("C:\\PM_DELETE_CARRIER_TEST_FOLDER\\"+carrier.getCarrierId()+"Carrier_BackUp_Restore.sql");
File file = new File("/app/jakarta-tomcat/logs/Carrier_BackUps/"+carrier.getCarrierId()+"Carrier_BackUp_Restore.sql");

You can make use of the System properties in Java. Say suppose Use "user.home" in your file path so that the file will be placed in the user home directory. You don't have to switch in between

Ex:

File file = new File(System.getProperty("user.home")+File.separator+
"Carrier_BackUp_Restore.sql");

Adding another way by @EJP comment to avoid file separator

File file = new File(System.getProperty("user.home"), "Carrier_BackUp_Restore.sql");

对于临时文件,可以让JVM为您选择合适的路径:请参见File.createTempFile

"My need is to open a file (temp file) and write something to it" . Why not use Files.createTempFile() but remember the file is not automatically deleted , You can use deleteOnExit() or open it via DELETE_ON_CLOSE options. If you want to create the file manually then use Paths

Paths.get("foo", "somelocation").toFile();

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