我们都知道,Java File类能够创建文件或者文件夹,但是不能两个一起创建,假设我需要在一个(或多层)尚未创建的文件夹下新建一个文件,那将会很麻烦。所以写了一个简单的工具来完成这件事情。
package kingsleylong;
import java.io.File;
import java.io.IOException;
/**
* This class provides methods to create new file/directory
* @author kingsleylong
*
*/
public class DirMaker {
/**
* Enhancement of java.io.File#createNewFile()
* Create the given file. If the parent directory don't exists, we will create them all.
* @param file the file to be created
* @return true if the named file does not exist and was successfully created; false if the named file already exists
* @see java.io.File#createNewFile
* @throws IOException
*/
public static boolean createFile(File file) throws IOException {
if(! file.exists()) {
makeDir(file.getParentFile());
}
return file.createNewFile();
}
/**
* Enhancement of java.io.File#mkdir()
* Create the given directory . If the parent folders don't exists, we will create them all.
* @see java.io.File#mkdir()
* @param dir the directory to be created
*/
public static void makeDir(File dir) {
if(! dir.getParentFile().exists()) {
makeDir(dir.getParentFile());
}
dir.mkdir();
}
public static void main(String args[]) {
String filePath = "C:/temp/a/b/c/d/e/f/g.txt";
File file = new File(filePath);
try {
System.out.println("file.exists()? " + file.exists());
boolean created = createFile(file);
System.out.println(created?"File created":"File exists, not created.");
System.out.println("file.exists()? " + file.exists());
} catch (IOException e) {
e.printStackTrace();
}
}
}