龙空技术网

微面试|JAVA源码:文件创建的三种

猿来是HelloWorld 75

前言:

如今你们对“怎么用java创建文件”大体比较重视,兄弟们都想要剖析一些“怎么用java创建文件”的相关知识。那么小编在网上收集了一些关于“怎么用java创建文件””的相关文章,希望我们能喜欢,朋友们一起来学习一下吧!

1.直接传字符串

public File(String pathname) {    if (pathname == null) {        throw new NullPointerException();    }    this.path = fs.normalize(pathname);    this.prefixLength = fs.prefixLength(this.path);}
2.字符串分为父路径和子文件名
public File(String parent, String child) {    if (child == null) {        throw new NullPointerException();    }    if (parent != null) {        if (parent.isEmpty()) {            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);}
3.字符串分为父类对象子以及文件名字
public File(File parent, String child) {        if (child == null) {            throw new NullPointerException();        }        if (parent != null) {            if (parent.path.isEmpty()) {                this.path = fs.resolve(fs.getDefaultParent(),                                       fs.normalize(child));            } else {                this.path = fs.resolve(parent.path,                                       fs.normalize(child));            }        } else {            this.path = fs.normalize(child);        }        this.prefixLength = fs.prefixLength(this.path);    }
例子:
package com.frank;import java.io.File;import java.io.IOException;public class file {    public static void main(String[] args) throws IOException {        createFile01();    }        public static void createFile01() throws IOException {        String fileName="E:\\leichao.txt";        File file1=new File(fileName);        file1.createNewFile();        System.out.println("创建文件成功");    }    }

标签: #怎么用java创建文件