简体   繁体   English

使用File for Unix / Windows创建Java目录

[英]Java create directory using File for Unix / Windows

I need to create a directory on unix machine. 我需要在unix机器上创建一个目录。 I think the below code will work fine on unix machine but fails while testing it on local windows machine. 我认为下面的代码在unix机器上运行正常但在本地windows机器上测试时失败了。 Where does this directory get created on my local machine ? 该目录在我的本地计算机上创建在哪里?

String xmlDir = "/home/data/logs"
File xmlDirectory = new File(xmlDir); 
xmlDirectory.mkdir();

I tried below directory path and it worked fine on windows machine. 我试过下面的目录路径,它在Windows机器上工作正常。 But i had to use the mkdirs() instead of mkdir() method which needs to be used for unix directory creation? 但我必须使用mkdirs()而不是mkdir()方法,它需要用于unix目录创建?

String xmlDir = "C:\\home\\data\\logs"
File xmlDirectory = new File(xmlDir); 
xmlDirectory.mkdirs();

How can I make it work locally as well as n unix machine ? 如何让它在本地以及n unix机器上运行? Is there a better way for File and Directory creation ? 是否有更好的文件和目录创建方法?

--Thanks-- - 谢谢 -

You should use the System user.home property which will return the user's home directory in a system independent manner, for example... 您应该使用System user.home属性,它将以系统无关的方式返回用户的主目录,例如......

 File home = new File(System.getProperty("user.home"));

mkdir will only create the last element in the path, where as mkdirs will create all the elements that do not exist. mkdir只会创建路径中的最后一个元素,而mkdirs将创建所有不存在的元素。 Using mkdirs is probably a slightly better idea as it ensures (where permissions allow) that all elements in the path will be created if they do not exist 使用mkdirs可能是一个稍好的想法,因为它确保(在权限允许的情况下)路径中的所有元素如果不存在则将被创建

You have already hit on the answer: Just use mkdirs() . 你已经找到了答案:只需使用mkdirs() It is not platform dependent. 它不依赖于平台。 However, if you include platform dependent nomenclature, then you'll run into trouble when moving the code from one environment to another. 但是,如果您包含平台相关的命名法,那么在将代码从一个环境移动到另一个环境时,您将遇到麻烦。 Just be sure to use platform independent code, or at the very least, check for the OS before doing so via System.getProperty("os.name"); 只需确保使用与平台无关的代码,或者至少在通过System.getProperty("os.name");执行此操作之前检查操作系统System.getProperty("os.name");

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

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