IO流——实现一个文件拷贝的功能

本文深入探讨了文件拷贝操作背后的IO流技术,包括流的分类、四大抽象类以及实现步骤。通过示例代码,展示了如何利用Java IO流进行文件复制,并处理可能出现的异常情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


IO流的三种分类方式
1.按流的方向分为:输入流和输出流
2.按流的数据单位不同分为:字节流和字符流

3.按流的功能不同分为:节点流和处理流二、IO流的四大抽象类:字符流:ReaderWriter字节流:InputStream(读数据)OutputStream(写数据)


示例:实现一个文件拷贝的功能

public static boolean copyFile(String filePath,String toFilePath) {

FileOutputStream fileOutputStream = null;
InputStreamReader read = null ;
try {
String encoding = "UTF-8";
File file = new File(filePath);

if (file.isFile() && file.exists()) {
//读待拷贝的文件
read = new InputStreamReader(
new FileInputStream(file), encoding);
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;

File tofile = new File(toFilePath);
//拷贝过去的位置 存在同名文件
if(tofile.exists()){
//System.out.print("同名文件存在");
throw new Exception("同名文件存在");
}else{
//拷贝
fileOutputStream = new FileOutputStream(toFilePath);
while ((lineTxt = bufferedReader.readLine()) != null) {
String content = lineTxt;
// 写
fileOutputStream.write(content.getBytes("UTF-8"));
}
}
return true;
} else {
//System.out.println("找不到文件");
throw new Exception("404-找不到文件");
}
} catch (Exception e) {
e.printStackTrace();
return false;
}finally{
try {
fileOutputStream.close();
read.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值