|
在编程中,经常要用到创建多级目录,下面通过java来实现:
import java.io.*;
import java.util.*;
public class CreateFolders{
public static void main(String[] args) {
String path="c:/aaa/bbb/ccc";
StringTokenizer st=new StringTokenizer(path,"/");
String path1=st.nextToken()+"/";
String path2 =path1;
while(st.hasMoreTokens())
{
path1=st.nextToken()+"/";
path2+=path1;
File inbox = new File(path2);
if(!inbox.exists())
inbox.mkdir();
}
}
}
而用的最多的莫过于根据日期来创建目录进行文章的分类,如20090915用它来在E盘下创建一个E:/2009/09/17的目录而20090917又是一个字符串,须将它转化为:2009/09/17这种格式才好创建目录,下面是我实现的方法:
import java.util.*;
import java.text.*;
import java.io.*;
public class Createdirs{
public static void main(String[] args) {
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
String dateString = "20090917";
try {
Date date = df.parse(dateString);
String path="E:/"+new SimpleDateFormat("yyyy/MM/dd").format(date);
//System.out.println(DateFormat.getDateInstance().format(date));
StringTokenizer st=new StringTokenizer(path,"/");
String path1=st.nextToken()+"/";
String path2 =path1;
while(st.hasMoreTokens())
{
path1=st.nextToken()+"/";
path2+=path1;
File inbox = new File(path2);
if(!inbox.exists())
inbox.mkdir();
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
} |
|