java 不存在就创建_Java 判断多级路径是否存在,不存在就创建
Java 判斷多級路徑是否存在,不存在就創(chuàng)建
方案一:
(帶文件名的Path:如:D:\news\2014\12\abc.text)
public boolean isexitsPath(String path)throws InterruptedException{
String [] paths=path.split("\\\\");
StringBuffer fullPath=new StringBuffer();
for (int i = 0; i < paths.length; i++) {
fullPath.append(paths[i]).append("\\\\");
File file=new File(fullPath.toString());
if(paths.length-1!=i){//判斷path到文件名時,無須繼續(xù)創(chuàng)建文件夾!
if(!file.exists()){
file.mkdir();
System.out.println("創(chuàng)建目錄為:"+fullPath.toString());
Thread.sleep(1500);
}
}
}
File file=new File(fullPath.toString());//目錄全路徑
if (!file.exists()) {
return true;
}else{
return false;
}
}
注意:帶文件名的path,需要判斷是否path中已經包含文件名,若包含,則不再創(chuàng)建文件夾。
(不帶文件名的Path:如:D:\news\2014\12)
public boolean isexitsPath(String path)throws InterruptedException{
String [] paths=path.split("\\\\");
StringBuffer fullPath=new StringBuffer();
for (int i = 0; i < paths.length; i++) {
fullPath.append(paths[i]).append("\\\\");
File file=new File(fullPath.toString());
if(!file.exists()){
file.mkdir();
System.out.println("創(chuàng)建目錄為:"+fullPath.toString());
Thread.sleep(1500);
}
}
File file=new File(fullPath.toString());//目錄全路徑
if (!file.exists()) {
return true;
}else{
return false;
}
}
方案二:
(帶文件名的Path:如:D:\news\2014\12\abc.text)
public static boolean isExist(String filePath) {
String paths[] = filePath.split("\\\\");
String dir = paths[0];
for (int i = 0; i < paths.length - 2; i++) {//注意此處循環(huán)的長度
try {
dir = dir + "/" + paths[i + 1];
File dirFile = new File(dir);
if (!dirFile.exists()) {
dirFile.mkdir();
System.out.println("創(chuàng)建目錄為:" + dir);
}
} catch (Exception err) {
System.err.println("ELS - Chart : 文件夾創(chuàng)建發(fā)生異常");
}
}
File fp = new File(filePath);
if(!fp.exists()){
return true; // 文件不存在,執(zhí)行下載功能
}else{
return false; // 文件存在不做處理
}
}
(不帶文件名的Path:如:D:\news\2014\12)
public static boolean isExist(String filePath) {
String paths[] = filePath.split("\\\\");
String dir = paths[0];
for (int i = 0; i < paths.length - 1; i++) {//注意此處循環(huán)的長度
try {
dir = dir + "/" + paths[i + 1];
File dirFile = new File(dir);
if (!dirFile.exists()) {
dirFile.mkdir();
System.out.println("創(chuàng)建目錄為:" + dir);
}
} catch (Exception err) {
System.err.println("ELS - Chart : 文件夾創(chuàng)建發(fā)生異常");
}
}
File fp = new File(filePath);
if(!fp.exists()){
return true; // 文件不存在,執(zhí)行下載功能
}else{
return false; // 文件存在不做處理
}
}
注意:帶文件名和不帶文件名的處理方式的區(qū)別就在于循環(huán)的長度上。
總結
以上是生活随笔為你收集整理的java 不存在就创建_Java 判断多级路径是否存在,不存在就创建的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 牛客网 JS编程
- 下一篇: JavaIO流加解密,AES对字符串加解