File file = new File(destFileName);
if(file.exists()) {
System.out.println("创建单个文件" + destFileName + "失败,目标文件已存在!");
return false;
}
if (destFileName.endsWith(File.separator)) {
System.out.println("创建单个文件" + destFileName + "失败,目标文件不能为目录!");
return false;
}
//判断目标文件所在的目录是否存在
if(!file.getParentFile().exists()) {
//如果目标文件所在的目录不存在,则创建父目录
System.out.println("目标文件所在目录不存在,准备创建它!");
if(!file.getParentFile().mkdirs()) {//创建目录并且返回创建结果
System.out.println("创建目标文件所在目录失败!");
return false;
}
}
//创建目标文件
try {
if (file.createNewFile()) { //当且仅当不存在具有此抽象路径名指定名称的文件时,不可分地创建一个新的空文件
System.out.println("创建单个文件" + destFileName + "成功!");
return true;
} else {
System.out.println("创建单个文件" + destFileName + "失败!");
return false;
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("创建单个文件" + destFileName + "失败!" + e.getMessage());
return false;
}
}
public static boolean createDir(String destDirName) {
File dir = new File(destDirName);
if (dir.exists()) {
System.out.println("创建目录" + destDirName + "失败,目标目录已经存在");
return false;
}
if (!destDirName.endsWith(File.separator)) {
destDirName = destDirName + File.separator;
}
//创建目录
if (dir.mkdirs()) { //mkdirs()可以建立多级文件夹, mkdir()只会建立一级的文件夹
System.out.println("创建目录" + destDirName + "成功!");
return true;
} else {
System.out.println("创建目录" + destDirName + "失败!");
return false;
}
}
public static String createTempFile(String prefix, String suffix, String dirName) {
File tempFile = null;
if (dirName == null) {
try{
//在默认文件夹下创建临时文件
tempFile = File.createTempFile(prefix, 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 (!createDir(dirName)) {
System.out.println("创建临时文件失败,不能创建临时文件所在的目录!");
return null;
}
}
try {
//在指定目录下创建临时文件
tempFile = File.createTempFile(prefix, suffix, dir);
return tempFile.getCanonicalPath();
} catch (IOException e) {
e.printStackTrace();
System.out.println("创建临时文件失败!" + e.getMessage());
return null;
}
}
}
public static void main(String[] args) {
//创建目录
String dirName = "G:/test";
createDir(dirName);
//创建文件
String fileName = dirName + "/test1/test1.txt";
createFile(fileName);
//创建临时文件
String prefix = "temp";
String suffix = ".txt";
for (int i = 0; i < 10; i++) {
System.out.println("创建了临时文件:"
+ createTempFile(prefix, suffix, dirName));
}
//在默认目录下创建临时文件
for (int i = 0; i < 10; i++) {
System.out.println("在默认目录下创建了临时文件:"
+ createTempFile(prefix, suffix, null));
}
}
//显示目录下所有子目录和文件
public static void tree(File f){
//判断传入对象是否为一个文件夹对象
if(!f.isDirectory()){//判断是否是目录
System.out.println("你输入的不是一个文件夹,请检查路径是否有误!!");
}
else{
File[] t = f.listFiles();
for(int i=0;i<t.length;i++){
//判断文件列表中的对象是否为文件夹对象,如果是则执行tree递归,直到把此文件夹中所有文件输出为止
if(t[i].isDirectory()){//目录
System.out.println("package\t"+t[i].getName());
tree(t[i]);
}
else{
System.out.println("File\t"+t[i].getName());
}
}
}
}