1.new File(String pathname)//根据路径构建一个file对象
2.new File(File parent,String child) //根据父目录文件+子路径构建
3. new File(String parent,String child) //根据父目录+子路径构建
最终在D盘下面创建了三个txt文件(命名为名字缩写)
以下为三种方式的源代码
package com.hspedu.file;
import org.junit.jupiter.api.Test;
import java.io.*;
public class FileCreate {
public static void main(String[] args) {
}
//方式1 new File(String pathname)
@Test
public void create01() {
String filePath = "e:\\news1.txt";
File file = new File(filePath);
try {
file.createNewFile();
System.out.println("文件创建成功");
} catch (IOException e) {
e.printStackTrace();
}
}
//方式2 new File(File parent,String child) //根据父目录文件+子路径构建
//e:\\news2.txt
@Test
public void create02() {
File parentFile = new File("e:\\");
String fileName = "news2.txt";
//这里的file对象,在java程序中,只是一个对象
//只有执行了createNewFile 方法,才会真正的,在磁盘创建该文件
File file = new File(parentFile, fileName);
try {
file.createNewFile();
System.out.println("创建成功~");
} catch (IOException e) {
e.printStackTrace();
}
}
//方式3 new File(String parent,String child) //根据父目录+子路径构建
@Test
public void create03() {
//String parentPath = "e:\\";
String parentPath = "e:\\";
String fileName = "news4.txt";
File file = new File(parentPath, fileName);
try {
file.createNewFile();
System.out.println("创建成功~");
} catch (IOException e) {
e.printStackTrace();
}
}
}
标签:file,IO,创建,流中,File,new,txt,public,String From: https://www.cnblogs.com/1713564464qq/p/16861949.html