创建文件对象相关构造器和方法:
(1)new File(String pathname)//根据路径构建一个file对象。
(2)new File(File parent,String child)//根据父目录文件+子路径构建。
(3)new File(String parent,String child)//根据父目录+子路径构建
createNewFile 创建新文件
第一种方式:
//根目录在D盘File file = new File("D:\\");//文件名为new.txtFile file1 = new File(file,"new.txt");try {//该方法将有异常,需要抛出..file1.createNewFile();} catch (IOException e) {throw new RuntimeException(e);}System.out.println("创建成功...");
第二种方式:
String filepath = "D:\\new1.txt";File file2 = new File(filepath);try {file2.createNewFile();} catch (IOException e) {throw new RuntimeException(e);}
第三种方式:
File file = new File("D:\\");String fileName = "new2.text";File file2 = new File(file, fileName);try {file2.createNewFile();} catch (Exception e) {throw new RuntimeException(e);}
总共三种方式,每种创建的时候都需要抛出异常,所以你必须要执行。