File类的createNewFile、mkdir和mkdirs

xiaoxiao2025-11-17  5

createNewFile()

用于创建文件,仅仅是文件,不包括文件夹(目录);

创建成功返回true,失败返回false。

当此抽象路径名不存在指定名称的文件时才创建;如果该路径下已有指定名称的文件,则不会创建,返回false。

当指定的抽象路径不存在时会报IOException:系统找不到指定的路径。例如:

假设指定的抽象路径名为“C:/Users/Desktop/djomega/test/test.txt”,

public class FileTest { public static void main(String[] args) throws IOException { File file = new File("C:/Users/Desktop/djomega/test/test.txt"); //如果"C:/Users/Desktop/djomega/test"不存在,就会报IOException:系统找不到指定的路径 file.createNewFile(); } }

mkdir()

用于创建此抽象路径名指定的文件的上一级目录。创建成功返回true,创建失败返回false;

仅仅是创建目录,不创建文件;

指定的文件名为test.txt,如果在“C:/Users/Desktop/djomega"下没有test这个目录,则会创建,返回true;反之,不创建,返回false。

但是,如果连djomega这个目录都没有,则返回false。

public class FileTest { public static void main(String[] args) throws IOException { File file = new File("C:/Users/Desktop/djomega/test/test.txt"); boolean b = file.getParentFile().mkdirs(); System.out.println(b); } }

mkdirs()

用于创建此抽象路径名指定的多级目录。创建成功返回true,创建失败返回false;

仅仅是创建目录,不创建文件;

如果存在则创建失败返回fasle;

如前面说的,连djomega这个目录都没有,mkdirs()也会创建。

public class FileTest { public static void main(String[] args) throws IOException { File file = new File("C:/Users/Desktop/djomega/test/test.txt"); boolean b = file.getParentFile().mkdirs(); System.out.println(b); } }

关于getParentFile()

要使用mkdir()或mkdirs()来创建目录,一定要使用getParentFile(),否则它会将文件也作为文件夹来创建;

即test.txt会作为一个目录被创建;

因为File即可以是文件,也可以是目录,哪怕有.txt后缀,它也会默认为目录而非文件;

 

转载请注明原文地址: https://www.6miu.com/read-5039799.html

最新回复(0)