使用IO流创建文件,三种方式
package IO流.CreateFile; import java.io.File; import java.io.IOException; /** * @program:多线程和IO * @descripton:创建新文件 * @author:ZhengCheng * @create:2021/10/4-13:24 **/ public class CreateNewFile { public static void main(String[] args) { CreateNewFile cnf = new CreateNewFile(); cnf.createNewFile01("e:\\new1.txt"); cnf.createNewFile02("e:\\","new2.txt"); cnf.createNewFile03("e:\\","new3.txt"); } //路径与文件名 public void createNewFile01(String filepath){ File file = new File(filepath); try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } //父路径+子名 public void createNewFile02(String father,String child){ File file = new File(father,child); try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } //父文件加子名字 public void createNewFile03(String father,String child){ File Ffile = new File(father); File file = new File(Ffile,child); try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } }
一些基本的File的API
public void fileInfo(){ File file = new File("e:\\new1.txt"); System.out.println("文件名字=" + file.getName()); System.out.println("文件绝对路径=" + file.getAbsolutePath()); System.out.println("文件父级目录=" + file.getParent()); System.out.println("文件大小(字节)=" + file.length()); System.out.println("文件是否存在=" + file.exists()); System.out.println("是不是一个文件=" + file.isFile()); System.out.println("是不是一个目录=" + file.isDirectory()); }
删除文件,一般的文件,和空文件夹,我们都可以直接使用delete删除。但是如果文件夹中存在东西,那么,我们需要使用别的方法。
基础删除方法:
File file = new File("e:\\new1.txt"); if (file.exists()){ file.delete(); }
删除内含文件的文件夹(包括该文件夹)
public void dirsDelete(String path) { File file = new File(path); String[] fileContent = file.list(); for (String conPath : fileContent) { File file1 = new File(file, conPath); //递归向下删除 if (file1.isDirectory()) { dirsDelete(file1.getAbsolutePath()); file1.delete();//空了,删除 } else { file1.delete(); } } file.delete();//删除最顶层父目录,没有这句话可以当做清空path文件夹。 }