利用Java的自带命令file.mkdirs();是可以直接在系统创建文件夹的。
比如在d:\1文件夹下创建一个2的文件夹,则这样写:
import java.io.*; public class FileMkdirTest { public static void main(String[] args) { File file = new File("d:\\1\\2"); //如果d:\1\2这个文件夹不存在,才创建 if (!file.exists()) { file.mkdirs(); } } }
Java把文件夹也视作一个file,
但值得注意的是,在文件夹或文件名中不得含有:两个方向的斜杠\/、冒号:、星号*、问号?、引号"、左右尖括号<>、竖杠|,你要使用这个符号作为文件夹或文件名称,最好把他们转化成全角\/:*?"<>|,可以利用到如下的JAVA函数转化:
public static String fileEncode(String str) { if (str != null) { //这里是专为文件写的转义方法,涉及文件操作 return str .replaceAll("\\\\", "\") .replaceAll("/", "/") .replaceAll(":", ":") .replaceAll("[*]", "*") .replaceAll("[?]", "?") .replaceAll("\"", "”") .replaceAll(":", ":") .replaceAll("<", "<") .replaceAll(">", ">") .replaceAll("[|]", "|"); } else { //防止空,搞成空格 return " "; } }
如果你在新建的文件夹中,中含有\/:*?"<>|,file.mkdirs();只会返回false,不会抛出任何异常,然后不创建文件夹,因此这个错误相当隐蔽。
比如如下的程序:
public class FileMkdirTest { public static void main(String[] args) { File file = new File("d:\\1\\|"); if (!file.exists()) { file.mkdirs(); } } }
在d:\1中的|文件夹创建失败,但Java控制台不返回任何信息,具体运行结果如下图:
时间: 2024-12-08 01:35:04