package Chapter07.file;
import java.io.File;
import java.io.IOException;
public class FileDemo_04 {
public static boolean createDirectory(String destDirName) {// 判断目录是否创建成功,成功则返回true,否则返回false
File dir = new File(destDirName);// 创建一个File对象
if (dir.exists()) {// 判断该目录是否存在,存在则返回false
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) {
e.printStackTrace();
System.out.println("创建临时文件失败!" + e.getMessage());
return null;
}
} else {
File dir = new File(dirName);
// 如果临时文件所在目录不存在,首先创建目录
if (!dir.exists()) {
if (FileDemo_04.createDirectory(dirName)) {
System.out.println("创建临时文件失败,不能创建临时文件所在的目录!");
return null;
}
}
try {
// 在指定目录下创建指定的文件
tempFile = File.createTempFile(fileName, suffix, dir);
return tempFile.getCanonicalPath();
} catch (IOException e) {
e.printStackTrace();
System.out.println("创建临时文件失败!" + e.getMessage());
return null;
}
}
}
public static void main(String[] args) {
String[] surfix = { ".txt", ".jpg", ".doc", ".excel", ".java", ".html",null,"" };
// 创建目录
String dirName = "D:\\temp\\temp1";
FileDemo_04.createDirectory(dirName);
// 创建临时文件
String fileName = "temp";
for (int i = 0; i < surfix.length; i++) {
System.out.println("成功创建了临时文件: "
+ FileDemo_04.createFiles(fileName, surfix[i], dirName));
}
}
}
- 1
- 2
前往页