简体   繁体   中英

Java create directory using File for Unix / Windows

I need to create a directory on unix machine. I think the below code will work fine on unix machine but fails while testing it on local windows machine. 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. But i had to use the mkdirs() instead of mkdir() method which needs to be used for unix directory creation?

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 ? 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...

 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. 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

You have already hit on the answer: Just use 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");

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