1、创建文件对象相关构造器和方法 new File(String pathname) //根据路径构建一个 File 对象 new File(File parent,String child) //根据父目录文件+子路径构建 new File(String parent,String child) //根据父目录+子路径构建 createNewFile() //创建文件 import org.testng.annotations.Test; import java.io.File; import java.io.IOException; public class FileCreate {public static void main(String[] args) { } //方式 1 @Test public void create1(){ String filePath = "D:\\file1.txt"; File file = new File(filePath); try { file.createNewFile(); System.out.println("创建文件 1 成功"); } catch (IOException e) { e.printStackTrace(); } } //方式 2 @Test public void create2(){ File parentFile = new File("D:\\"); String fileNane = "file2.txt";File file = new File(parentFile, fileNane); try { file.createNewFile(); System.out.println("文件 2 创建成功"); } catch (IOException e) { throw new RuntimeException(e); } } //方式三 @Test public void create3(){ String parentPath = "d:\\"; String filePath = "file3.txt"; File file = new File(parentPath, filePath); try { file.createNewFile(); System.out.println("文件 3 创建成功");} catch (IOException e) { throw new RuntimeException(e); } } }
标签:File,代码,createNewFile,课上,file,new,public,String From: https://www.cnblogs.com/tscky/p/16861691.html