Java 创建文件或者文件夹

本文介绍了一种使用Java批量创建多级文件夹及指定文件的方法。通过增强File类的功能,实现了一次性创建不存在的多级目录结构及其下的文件,简化了开发流程。
源:http://kingsleylong.iteye.com/blog/1447556
评:
我们都知道,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();
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值