import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* IO操作
* 1.注意追加写和覆盖写
* 2.流只能对文件进行操作
* 3.流的关闭规则:先开后关
* 4.read():返回当前读取的字节长度
* 5.常用语法
* File file = new File(String path);
* File file = new File(String parent, String child);
* File file = new File(File parent, String child);
* InputStream = new FileInputStream(String path);
* InputStream = new FileInputStream(String path, boolean flag);
* InputStream = new FileInputStream(File file);
* InputStream = new FileInputStream(File file, boolean flag);
* @author pengjunzhao
* @date 2017年12月25日
*/
public class MyIO {
public static void main(String[] args) throws IOException {
//文件夹复制(递归)
directoryCopy("G:/other/2.jpg", "G:/download");
}
/**
* 文件夹复制
* @param srcPath 源文件夹路径
* @param destPath 目标文件夹路径
* @throws IOException
*/
public static void directoryCopy(String srcPath, String destPath) throws IOException{
File src = new File(srcPath);
File dest = new File(destPath);
//1、目标文件夹是否存在且为目录,若不存在就创建
if(!dest.exists() && dest.isDirectory()){
dest.mkdirs();
}else if(dest.isFile()){
System.out.println("目标文件夹路径不能为文件类型");
return;
}
//开始复制
directoryCopyDetail(src, dest);
}
//文件夹复制详情
public static void directoryCopyDetail(File src, File dest) throws IOException{
//2.源目标是文件夹且目标文件子一级目录中不存在该文件夹就创建它
File newFile = new File(dest, src.getName());
if(src.isDirectory()){
newFile.mkdirs(); //目标文件夹中创建新目录
for(File sub:src.listFiles()){
//3.遍历文件夹,是文件就复制,是目录就重复调用本方法
directoryCopyDetail(sub, newFile);
}
}else if(src.isFile()){
fileCopy(src, newFile); //目标文件夹中创建文件
}
}
/**
* 文件复制
* @param srcPath
* @param destPath
* @throws IOException
*/
public static void fileCopy(File srcPath, File destPath) throws IOException{
if(!srcPath.isFile()){
System.out.println("源路径不是一个文件类型");
return;
}
/*
* 此处不必对destPath进行判断
* 因为:程序输出到文件时,当且仅当文件不存在时,会直接创建文件。当该文件父目录不存在时会报错
*/
//4.流实现文件内容复制
InputStream is = new FileInputStream(srcPath); //输入流,从文件写入程序
OutputStream os = new FileOutputStream(destPath, false); //输出流,从程序输出到文件(硬盘)。true表示追加写操作(默认覆盖写)
byte[] bt = new byte[1024];
int len = 0; //当前读取到的字节数
//顺序读取
while(-1 != (len=is.read(bt, 0 ,1024))){
//顺序写入
os.write(bt, 0, len);
}
os.flush();
os.close();
is.close();
}
}
IO流操作一 :源文件/源文件夹 复制到指定目录
最新推荐文章于 2022-05-17 16:37:12 发布