简体   繁体   English

可以同时用于UNIX和Windows的Java文件名

[英]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) 我需要打开一个文件(临时文件)并向其中写入一些内容,该怎么做才能使其适用于所有操作系统类型(至少适用于Unix和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) 下面是我当前的代码,每次我想在Windows上测试某些东西时,我都会在这些行之间切换(注释/取消注释)

//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. 您可以使用Java中的System属性 Say suppose Use "user.home" in your file path so that the file will be placed in the user home directory. 假设在文件路径中使用"user.home" ,以便将文件放置在用户主目录中。 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 通过@EJP注释添加另一种方法以避免文件分隔符

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. 为什么不使用Files.createTempFile()但要记住该文件没有被自动删除 ,则可以使用deleteOnExit()或通过DELETE_ON_CLOSE选项打开它。 If you want to create the file manually then use Paths 如果要手动创建文件,请使用路径

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM