需求:
将文件从src文件夹中拷贝到desc文件夹中,需要考虑子文件夹。
扩展:
File类的常用方法:
File类常用方法:大致有以下几种:
- isDirectory() 是否为文件夹
- isFile() 是否为文件
- getPath() 得到file的路径
- getName() 得到文件或文件夹的名字(文件包含后缀)
- getParent() 得到去掉最后一层的路径
- mkdir() 创建新文件夹,只能创建一层
- mkdirs() 创建新文件夹,可以多层
- createNewFile() 创建新文件,只能一层
- exists() 路径是否存在
- delete() 删除文件或者空目录
- list() 返回该路径下文件或者文件夹的名字数组
- listFiles() 返回该路径下文件或者文件夹组成的File数组
FileOutputStream类的常用方法:
- write(int b) 一个字节一个字节的写
- write(byte[] b) 一次写一个字节数组
- write(byte[] b,int off,int len)一次写入一个字节数组的一部分,off是起始序号,len是长度
FileInputStream类的常用方法:
- read(int b) 一个字节一个字节的读
- read(byte[] b) 一次读入一个字节数组
- read(byte[] b,int off,int len)一次读入一个字节数组的一部分,off是起始序号,len是长度
import java.io.*;
public class Filetest {
public static void main(String[] args) throws IOException {
//把文件从一个文件夹拷贝到另一个文件夹,考虑子文件夹
//要拷贝的文件路径
File src=new File("C:\\Users\\Lan\\Desktop\\学习\\Java\\src");
//要拷贝到的目的地文件夹
File desc=new File("C:\\Users\\Lan\\Desktop\\学习\\Java\\desc");
//拷贝的方法
copy(src,desc);
}
private static void copy(File src, File desc) throws IOException {
//如果目的地文件夹不存在就创建一个
desc.mkdirs();
//将src中的文件和文件夹存在File数组中
File[] files = src.listFiles();
//遍历数组
for (File file : files) {
if(file.isFile()){
//是文件就直接传
FileInputStream fis=new FileInputStream(new File(src,file.getName()));
FileOutputStream fos=new FileOutputStream(new File(desc,file.getName()));
byte[] bytes=new byte[1024];
int len;
while((len=fis.read(bytes)) != -1){
fos.write(bytes,0,len);
}
fos.close();
fis.close();
}else{
//是文件夹就递归,再次调用copy()方法
copy(new File(src,file.getName()),new File(desc,file.getName()));
}
}
}
}