47、创建临时文件
47、指定目录下创建临时文件
import java.io.File;
import java.io.IOException;
//在指定的目录下根据文件名前缀、扩展名来创建多个临时文件 public class CreateTemporaryFile {
// 判断目录是否创建成功,成功则返回true
public static boolean createDirectory(String destDirName) {
// 创建一个File对象
File dir = new File(destDirName);
// 判断该目录是否存在,存在则返回false
if (dir.exists()) {
return false;
}
// 如果该目录路径不是以文件分隔符结尾的则给起加上文件分隔符
if (!destDirName.endsWith(File.separator)) {
destDirName = destDirName + File.separator;
}
// 创建目标目录
if (dir.mkdirs()) {
System.out.println("指定目录不存在,创建目录" + destDirName +
"成功。");
return true;
} else {
System.out.println("创建目录" + destDirName + "失败。。");
return false;
}
}
// 根据传入的文件名的前缀和扩展名在指定的目录下创建文件
public static String createFiles(String fileName, String suffix,
String dirName) {
File tempFile = null;
if (dirName == null) {
// 在默认文件夹下创建临时文件
try {
tempFile = File.createTempFile(fileName, suffix);
// 返回临时文件的路径
return tempFile.getCanonicalPath();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("创建临时文件失败。。。" + e.getMessage());
return null;
}
} else {
File dir = new File(dirName);
// 如果临时文件所在的目录不存在,就创建目录
if (!dir.exists()) {
if (CreateTemporaryFile.createDirectory(dirName)) {
System.out.println("创建临时文件失败,不能创建临时文件所在的目录。。。。");
return null;
}
}
try {
tempFile = File.createTempFile(fileName, suffix, dir);
return tempFile.getCanonicalPath();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("创建临时文件失败。。。。。");
return null;
}
}
}
public static void main(String[] args) {
String[] surfix = { ".txt", ".jpg", ".doc", ".excel", ".java", ".html",
null, "" };
// 创建目录
String dirName = "D:\\temp\\temp1";
CreateTemporaryFile.createDirectory(dirName);
// 创建临时文件
String fileName = "temp";
for (int i = 0; i < surfix.length; i++) {
System.out.println("成功创建了临时文件:"
+ CreateTemporaryFile.createFiles(fileName,
surfix[i],
dirName));
}
}
}