java创建文件夹代码_Java创建文件夹及文件实例代码
package com.xhkj.util;
import java.io.File;
import java.io.IOException;
public class CreateFileUtil {
public static boolean CreateFile(String destFileName) {
File file = new File(destFileName);
if (file.exists()) {
System.out.println("創(chuàng)建單個(gè)文件" + destFileName + "失敗,目標(biāo)文件已存在!");
return false;
}
if (destFileName.endsWith(File.separator)) {
System.out.println("創(chuàng)建單個(gè)文件" + destFileName + "失敗,目標(biāo)不能是目錄!");
return false;
}
if (!file.getParentFile().exists()) {
System.out.println("目標(biāo)文件所在路徑不存在,準(zhǔn)備創(chuàng)建。。。");
if (!file.getParentFile().mkdirs()) {
System.out.println("創(chuàng)建目錄文件所在的目錄失敗!");
return false;
}
}
// 創(chuàng)建目標(biāo)文件
try {
if (file.createNewFile()) {
System.out.println("創(chuàng)建單個(gè)文件" + destFileName + "成功!");
return true;
} else {
System.out.println("創(chuàng)建單個(gè)文件" + destFileName + "失敗!");
return false;
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("創(chuàng)建單個(gè)文件" + destFileName + "失敗!");
return false;
}
}
public static boolean createDir(String destDirName) {
File dir = new File(destDirName);
if(dir.exists()) {
System.out.println("創(chuàng)建目錄" + destDirName + "失敗,目標(biāo)目錄已存在!");
return false;
}
if(!destDirName.endsWith(File.separator))
destDirName = destDirName + File.separator;
// 創(chuàng)建單個(gè)目錄
if(dir.mkdirs()) {
System.out.println("創(chuàng)建目錄" + destDirName + "成功!");
return true;
} else {
System.out.println("創(chuàng)建目錄" + destDirName + "成功!");
return false;
}
}
public static String createTempFile(String prefix, String suffix, String dirName) {
File tempFile = null;
try{
if(dirName == null) {
// 在默認(rèn)文件夾下創(chuàng)建臨時(shí)文件
tempFile = File.createTempFile(prefix, suffix);
return tempFile.getCanonicalPath();
}
else {
File dir = new File(dirName);
// 如果臨時(shí)文件所在目錄不存在,首先創(chuàng)建
if(!dir.exists()) {
if(!CreateFileUtil.createDir(dirName)){
System.out.println("創(chuàng)建臨時(shí)文件失敗,不能創(chuàng)建臨時(shí)文件所在目錄!");
return null;
}
}
tempFile = File.createTempFile(prefix, suffix, dir);
return tempFile.getCanonicalPath();
}
} catch(IOException e) {
e.printStackTrace();
System.out.println("創(chuàng)建臨時(shí)文件失敗" + e.getMessage());
return null;
}
}
public static void main(String[] args) {
// 創(chuàng)建目錄
String dirName = "c:/test/test0/test1";
CreateFileUtil.createDir(dirName);
// 創(chuàng)建文件
String fileName = dirName + "/test2/testFile.txt";
CreateFileUtil.CreateFile(fileName);
// 創(chuàng)建臨時(shí)文件
String prefix = "temp";
String suffix = ".txt";
for(int i = 0; i < 10; i++) {
System.out.println("創(chuàng)建了臨時(shí)文件:" + CreateFileUtil.createTempFile(prefix, suffix, dirName));
}
}
}
總結(jié)
以上是生活随笔為你收集整理的java创建文件夹代码_Java创建文件夹及文件实例代码的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 如何用python爬虫薅羊毛_不会Pyt
- 下一篇: Java中divide用法_java的B