`
kingsleylong
  • 浏览: 54950 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Java 创建文件或者文件夹

    博客分类:
  • Java
阅读更多

我们都知道,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();
		}
	}
}

分享到:
评论
3 楼 sxdtzhaoxinguo 2014-03-14  
   
2 楼 kingsleylong 2012-05-03  
隐者醉逍遥 写道
dir.mkdirs();  

谢谢提醒。没有仔细查阅API,重复了部分工作。
1 楼 隐者醉逍遥 2012-04-17  
dir.mkdirs();  

相关推荐

Global site tag (gtag.js) - Google Analytics