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("Create a single file" + destFileName + "Failed, the target file already exists!");
return false;
}
if (destFileName.endsWith(File.separator)) {
System.out.println("Create a single file" + destFileName + "Failed, the target cannot be a directory!");
return false;
}
if (!file.getParentFile().exists()) {
System.out.println("The path to the target file does not exist, prepare to create it...");
if (!file.getParentFile().mkdirs()) {
System.out.println("Failed to create the directory where the directory file is located!");
return false;
}
}
//Create target file
try {
if (file.createNewFile()) {
System.out.println("Create a single file" + destFileName + "Success!");
return true;
} else {
System.out.println("Create a single file" + destFileName + "Failed!");
return false;
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("Create a single file" + destFileName + "Failed!");
return false;
}
}
public static boolean createDir(String destDirName) {
File dir = new File(destDirName);
if(dir.exists()) {
System.out.println("Create directory" + destDirName + "Failed, the target directory already exists!");
return false;
}
if(!destDirName.endsWith(File.separator))
destDirName = destDirName + File.separator;
//Create a single directory
if(dir.mkdirs()) {
System.out.println("Create directory" + destDirName + "Success!");
return true;
} else {
System.out.println("Create directory" + destDirName + "Success!");
return false;
}
}
public static String createTempFile(String prefix, String suffix, String dirName) {
File tempFile = null;
try{
if(dirName == null) {
//Create temporary files in the default folder
tempFile = File.createTempFile(prefix, suffix);
return tempFile.getCanonicalPath();
}
else {
File dir = new File(dirName);
// If the directory where the temporary file is located does not exist, create it first
if(!dir.exists()) {
if(!CreateFileUtil.createDir(dirName)){
System.out.println("Failed to create temporary file, cannot create the directory where the temporary file is located!");
return null;
}
}
tempFile = File.createTempFile(prefix, suffix, dir);
return tempFile.getCanonicalPath();
}
} catch(IOException e) {
e.printStackTrace();
System.out.println("Failed to create temporary file" + e.getMessage());
return null;
}
}
public static void main(String[] args) {
//Create directory
String dirName = "c:/test/test0/test1";
CreateFileUtil.createDir(dirName);
//Create file
String fileName = dirName + "/test2/testFile.txt";
CreateFileUtil.CreateFile(fileName);
//Create temporary file
String prefix = "temp";
String suffix = ".txt";
for(int i = 0; i < 10; i++) {
System.out.println("A temporary file was created:" + CreateFileUtil.createTempFile(prefix, suffix, dirName));
}
}
}