package com.company.main;
import java.io.File;
import java.io.IOException;
public class CreateFileUtil {
public static boolean CreateFile(StringdestFileName){
File file = newFile(destFileName);
if(file.exists()){
System.out.println("创建单个文件"+ destFileName + "失败,目标文件已存在!");
returnfalse;
}
if(destFileName.endsWith(File.separator)){//路径分隔符
System.out.println("创建单个文件"+ destFileName + "失败,目标不能是目录!");
returnfalse;
}
if(!file.getParentFile().exists()){
System.out.println("目标文件所在路径不存在,准备创建。。。");
if(!file.getParentFile().mkdirs()){
System.out.println("创建目录文件所在的目录失败!");
returnfalse;
}
}
//创建目标文件
try{
if(file.createNewFile()){
System.out.println("创建单个文件"+destFileName + "成功!");
returntrue;
}else{
System.out.println("创建单个文件"+ destFileName + "失败!");
returnfalse;
}
}catch(IOException e){
e.printStackTrace();
System.out.println("创建单个文件"+ destFileName + "失败!");
returnfalse;
}
}
public static boolean createDir(StringdestDirName){
File dir = newFile(destDirName);
if(dir.exists()){
System.out.println("创建目录"+ destDirName + "失败,目标目录已存在!");
returnfalse;
}
if(!destDirName.endsWith(File.separator))
destDirName =destDirName + File.separator;
//创建单个目录
if(dir.mkdirs()){//该目录(或多级目录)能被创建则true否则false
System.out.println("创建目录"+ destDirName + "成功!");
returntrue;
}else{
System.out.println("创建目录"+ destDirName + "失败!");
returnfalse;
}
}
public static String createTempFile(Stringprefix, String suffix,
StringdirName){
File tempFile = null;
try{
if(dirName ==null){
//在默认文件夹下创建临时文件
tempFile= File.createTempFile(prefix, suffix);
returntempFile.getCanonicalPath();
}else{
Filedir = new File(dirName);
//如果临时文件所在目录不存在,首先创建
if(!dir.exists()){
if(!CreateFileUtil.createDir(dirName)){
System.out.println("创建临时文件失败,不能创建临时文件所在目录!");
returnnull;
}
}
tempFile= File.createTempFile(prefix, suffix, dir);
returntempFile.getCanonicalPath();
}
}catch(IOException e){
e.printStackTrace();
System.out.println("创建临时文件失败"+ e.getMessage());
returnnull;
}
}
public static void main(String[] args){
// 创建目录
String dirName ="c:/test/test0/test1";
CreateFileUtil.createDir(dirName);
// 创建文件
String fileName = dirName +"/test2/testFile.txt";
CreateFileUtil.CreateFile(fileName);
// 创建临时文件
String prefix = "temp";
String suffix = ".txt";
for(int i = 0; i< 10; i++){
System.out.println("创建了临时文件:"+CreateFileUtil.createTempFile(prefix, suffix, dirName));
}
}
}