day11 基于io流的文本拷贝_正在学习java中---的博客-爱代码爱编程
1.创建流
2.选择流
3.进行操作
4.释放空间
package day2;
import java.io.*;
public class iotest4 {
public static void main(String[] args) {
Copy("123.txt","dest.txt");
}
//封装成一个方法,前面输入源文件,后面输入复制的地址
public static void Copy(String copysrc,String copydest){
//创建源
File src = new File(copysrc);//源文件
File dest = new File(copydest);//目标文件
//选择流
InputStream is = null;
OutputStream tcp = null;
try {//捕获异常
is = new FileInputStream(src);
tcp = new FileOutputStream(dest);
//操作(分段读取)
byte[] car = new byte[1024];//定义一个缓冲容器
int len ;//接收长度
while ((len = is.read(car)) != -1) {//读取car中,如果没有数据就是-1
//字符数组转变为字符串或者叫解码
String str= new String(car, 0, len);;//负责将数据读取出来
tcp.write(car, 0, len);//直接写入地址文件
}
tcp.flush();//刷新此输出流,并强制将任何缓冲的输出字节写入流。
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {//释放资源,先运行的后关闭
if (null != tcp) {
try {
tcp.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
if (null != is) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}