Java基础回顾 : 利用字节流实现文件的拷贝

时间:2021-10-28 20:58:28

本文是一个范例 : 利用字节流实现文件的拷贝

package example;
/**
* 文件的拷贝.
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class TestDemo {
public static void main(String[] args) {
String srcPath = "e:\\test.txt";
String destPath = "e:\\msg\\info.txt";
try {
copyFile(srcPath,destPath);
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 利用字节流来实现文件的复制(字节流可以处理一切数据)
* @param srcPath : 源文件路径
* @param destPath : 目标文件路径
* @throws Exception
*/
public static void copyFile(String srcPath,String destPath) throws Exception{
//构建源文件和目标文件的File对象
File src = new File(srcPath);
File dest = new File(destPath);
//如果源文件不存在,抛出异常
if(!src.exists()){
throw new IOException("文件不存在!");
}
//如果目标文件父路径不存在,创建父路径
if(!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
//实例化输入流和输出流
InputStream is = new FileInputStream(src);
OutputStream os = new FileOutputStream(dest);
//定义缓冲字节数组,用来接收读取的内容
byte buf[] = new byte[1024];
int len = 0;
while((len=is.read(buf))!=-1) {
os.write(buf,0,len);
os.flush();
}
//关闭流
os.close();
is.close();
}
}