一、简介
- File类和四大家族没有关系,所有File类不能完成文件的读和写
- File对象是什么

二、常用方法
1.
package javase.day31.io;import java.io.File;import java.io.IOException;public class FileTest01 { public static void main(String[] args) throws IOException { //创建一个File对象 File f1 = new File("D\\file"); //判断是否存在 System.out.println(f1.exists()); //如果不存在,则以文件的形式创建出来// if (!f1.exists()){// f1.createNewFile();// } //以目录的形式新建// if (!f1.exists()){// f1.mkdir();// }// //创建多重目录// File f2 = new File("D:/a/b/c");// if (!f2.exists()){// f2.mkdirs();// } //获取文件的父路径 File f3 = new File(""); }}
2

3

4.获取文件最后一次修改时间
5.获取文件大小

6.listFile方法(获取当前目录下所有的子文件)

7.负责文件
package day31.homework;import java.io.*;public class CopyAll { public static void main(String[] args) { //拷贝源 File srcFile = new File("D:\\学习ppt"); //拷贝目标 File destFile = new File("C:\\"); //拷贝方法 copyDir(srcFile,destFile); } /** * * @param srcFile 拷贝源 * @param destFile 拷贝目标 */ private static void copyDir(File srcFile, File destFile) { if (srcFile.isFile()){ FileInputStream in = null; FileOutputStream out = null; try { //读这个文件 in = new FileInputStream(srcFile); //写到这个文件中 String path = (destFile.getAbsolutePath().endsWith("\\") ? destFile.getAbsolutePath(): destFile.getAbsolutePath()+"\\") + srcFile.getAbsolutePath().substring(3); out = new FileOutputStream(path); //一边读一边写 byte[] bytes = new byte[1024 * 1024]; int readCount = 0; while ((readCount = in.read(bytes))!= -1){ out.write(bytes,0,readCount); } out.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (out != null){ try { out.close(); } catch (IOException e) { e.printStackTrace(); } } if (in != null){ try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } //文件就不用调用,递归结束 return; } //获取源下面的子目录 File[] files = srcFile.listFiles(); for (File file : files){// 获取所有文件的绝对路径// System.out.println(file.getAbsolutePath()); if (file.isDirectory()){ //新建目录 String srcDir = file.getAbsolutePath();// String destDir = "C:\\"+ srcDir.substring(3); //动态获取 String destDir = (destFile.getAbsolutePath().endsWith("\\")? destFile.getAbsolutePath(): destFile.getAbsolutePath()+"\\") + srcFile.getAbsolutePath().substring(3); System.out.println(destDir); File newFile = new File(destDir); if (!newFile.exists()){ newFile.mkdirs(); } } //递归 copyDir(file,destFile); } }}