首先,你不要被File给迷惑了,中文翻译是个文件的意思,但Java中它表示的是“文件和目录路径名的抽象表示形式”,也就是说File即可以是文件,也可以是目录路径名;其次,File f=new File(dir,fileName); 这根据dir路径名字符串和fileName路径名字符串创建一个新 File实例,也就是说你认为fileName表示的是个文件, 而Java认为fileName可以是个文件和目录路径;所以这样调用f.mkdirs(),就会创建f表示的路径名指定的目录(包括dir和fileName),因为你明确的要创建目录;
你在f.getParentFile().mkdirs()后,再f.createNewFile(),这样Java才知道你要创建一个fileName的文件;
你在f.getParentFile().mkdirs()后,再f.createNewFile(),这样Java才知道你要创建一个fileName的文件;
* Creates a new <code>File</code> instance from a parent pathname string
* and a child pathname string.
*
* <p> If <code>parent</code> is <code>null</code> then the new
* <code>File</code> instance is created as if by invoking the
* single-argument <code>File</code> constructor on the given
* <code>child</code> pathname string.
*
* <p> Otherwise the <code>parent</code> pathname string is taken to denote
* a directory, and the <code>child</code> pathname string is taken to
* denote either a directory or a file. If the <code>child</code> pathname
* string is absolute then it is converted into a relative pathname in a
* system-dependent way. If <code>parent</code> is the empty string then
* the new <code>File</code> instance is created by converting
* <code>child</code> into an abstract pathname and resolving the result
* against a system-dependent default directory. Otherwise each pathname
* string is converted into an abstract pathname and the child abstract
* pathname is resolved against the parent.
*
* @param parent The parent pathname string
* @param child The child pathname string
* @throws NullPointerException
* If <code>child</code> is <code>null</code>
*/
public File(String parent, String child) {
if (child == null) {
throw new NullPointerException();
}
if (parent != null) {
if (parent.equals("")) {
this.path = fs.resolve(fs.getDefaultParent(),
fs.normalize(child));
} else {
this.path = fs.resolve(fs.normalize(parent),
fs.normalize(child));
}
} else {
this.path = fs.normalize(child);
}
this.prefixLength = fs.prefixLength(this.path);
}
f.mkdirs();
f.getParentFile().mkdirs();
2个不同之处
mydir1/mydir2/new .txt第一个是以new.txt为基准,所以mydir1/mydir2/new.txt都是文件夹,,
第二个是以mydir2为基准建立,所以是 mydir1/mydir2是文件夹
f.createNewFile();//创建名称为new.txt的文件
f.mkdirs();//创建名为new.txt的文件夹
f.getParentFile().mkdir();//由于f.getParentFile()为mydir2,即创建名为mydir2的文件夹,由于已经存在,故无需新建新的文件夹。
f.mkdirs();
f.getParentFile().mkdirs();
2个不同之处
先思考下再提问!
f是个File对象,f.getParentFile()也是个File对象,同样调用mkdirs(),它们的行为不一样吗?这与你这样创建File f=new File(dir,fileName),调用f.mkdirs();
和File parentPath=new File(dir);调用parentPath.mkdirs();
与你上面的是一样吗?只说到这,自己再继续学习。