注意:
代码中路径出现的分隔符必须使用双正斜杠或者单反斜杠,因为单正斜杠在java会被识别为转义符,如需要跨平台使用代码。则需要使用
String separator = System.getProperty("file.separator");
获取当前系统的文件分隔符 ,然后通过拼接字符串的方式拼接入路径
package io.stream.file;
import java.io.File;
import java.io.IOException;
public class 文件创建 {
public static void main(String[] args) {
//File file = new File(pathname);使用第一种构造方法创建一个文件
//如果父目录不存在则报错NullPrintException
try {
File file = new File("D:\\IOStream\\text1.txt");
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
//File file = new File(parent:StringPath,child:path);使用第二种构造方法创建一个文件
//根据String类型的父路径和子路径创建文件
//出现的路径必须存在,否则会报错
try {
File file = new File("D:\\IOStream\\","text2.txt");
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
//File file = new File(parent:filePath,child:path);使用第三种构造方法创建一个文件
//根据File类型的父路径和子路径创建文件
//出现的路径必须存在,否则会报错
//此方法推荐使用,比较灵活,可以在使用filepath.mkdirs方法在路径不存在的情况下
//逐级创建路径:示例如下
try {
File filepath = new File("D:\\IOStream\\");
if (filepath.exists()) {//判断当前路径是否存在
filepath.mkdirs(); //如果不存在则进入逐级创建文件夹
}
File file = new File(filepath,"text3.txt");
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}