什么是File类?
File和IO流的四大家族没有关系,所以File不能完成文件的读和写,File对象可能是目录也可能是文件
File对象指的是:
文件和目录路径名的抽象表示形式
上面图片中所有的都是File
D:\有道云词典\Dict\YoudaoDict.exe
这也是个File
package com.wcc.test;
import java.io.File;
import java.io.IOException;
/**
* @Author kk
* @Date 2020/3/30 19:55
*/
public class Demo3 {
public static void main(String[] args) throws IOException {
//创建一个File对象
File file = new File("F:\\temp");
//判断文件存不存在
System.out.println(file.exists());
/*
//如果不存在就以文件的形式创建
if (!file.exists()){
file.createNewFile();
}
*/
//如果文件不存在就以目录的形式创建出来
if (!file.exists()){
file.mkdir();
}
}
}
文件目录的拷贝:
package com.wcc.test;
import java.io.*;
/**
* 将一个目录从一个盘拷贝到另一个盘
* @Author kk
* @Date 2020/3/30 20:11
*/
public class Copy {
public static void main(String[] args) throws IOException {
//拷贝源
File srcfile = new File("C:\\Users\\kk\\Desktop\\新建文件夹");
//拷贝去向 F:\mubiaowenjiajia
File destfile = new File("F:\\mubiaowenjiajia");
//调用方法拷贝
copyDir(srcfile, destfile);
}
/**
* 拷贝目录的方法
*
* @param srcfile 拷贝源
* @param destfile 拷贝去向
*/
private static void copyDir(File srcfile, File destfile) throws IOException {
//如果是一个文件,递归结束。
//因为我给的srcFile是一个文件夹,先判断isFile,false,执行遍历
if (srcfile.isFile()) {
FileInputStream in = null;
FileOutputStream out = null;
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 * 2];
int readCount = 0;
while((readCount = in.read(bytes)) != -1){
out.write(bytes,0,readCount);
}
try {
assert false;
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
return;
} else{
File[] files = srcfile.listFiles();
for (File file : files) {
if (file.isDirectory()){
String src = file.getAbsolutePath();
String dest = (destfile.getAbsolutePath().endsWith("\\") ? destfile.getAbsolutePath() : destfile.getAbsolutePath() + "\\") + src.substring(3);
File file1 = new File(dest);
if(!file1.exists()){
file1.mkdirs();
}
}
copyDir(file,destfile);
}
}
}
}