使用文件输入流和输出流实现文件拷贝
程序员文章站
2022-04-09 16:46:55
...
文件拷贝
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;
/**
* @author 黑羽-孤高之银风
* @version 创建时间:2019年6月12日 上午10:31:51
* 使用文件输入流和输出流实现文件拷贝
*/
public class CopyFile {
public static void main(String[] args){
copyFile("C:/Users/XX/Desktop/start.txt","C:/Users/XX/Desktop/end.txt");
}
public static void copyFile(File src,File dest){
//1.选择流
InputStream is=null;
OutputStream os=null;
try {
is=new FileInputStream(src);
os=new FileOutputStream(dest);
//2.准备卡车
byte[] car=new byte[1024];
//3.读入写出
int len=-1; //读入到小卡车中数据的个数
while((len=is.read(car))!=-1){
os.write(car,0,len);
}
//4.刷出
os.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
//5.关闭 先打开的后关闭
try {
//多行添加try..catch=>alt+shift+z
if(os!=null){
os.close();
}
if(is!=null){
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//封装好的复制文件方法
public static void copyFile(String srcPath,String destPath){ //开始路径 目标路径
//1.创建源
File src = new File(srcPath);
File dest = new File(destPath);
//2.选择流
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(src);
os = new FileOutputStream(dest);
//3.操作★★★
byte[] flush = new byte[1024];//缓冲容器
int len = -1;
if ((len=is.read(flush))!=-1) {
os.write(flush, 0, len);
}
os.flush();//刷出
} catch (Exception e) {
}finally {
//4.关闭流
if (os!=null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is!=null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
下一篇: console对象
推荐阅读
-
Android中文件读写(输入流和输出流)操作小结
-
Java利用文件输入输出流实现文件夹内所有文件拷贝到另一个文件夹
-
文件输入输出流 OutputStrea字节输出流,InputStream字节输入流,Writer字符输出流,Reader字符输入流,转换流,拷贝原始实现详解
-
Android中文件读写(输入流和输出流)操作小结
-
Java利用文件输入输出流实现文件夹内所有文件拷贝到另一个文件夹
-
IO流操作三 : 使用字节数组流实现文件的拷贝
-
文件输入输出流 OutputStrea字节输出流,InputStream字节输入流,Writer字符输出流,Reader字符输入流,转换流,拷贝原始实现详解
-
使用文件输入流和输出流实现文件拷贝
-
【JAVA】IO之使用字节输入流和字节输出流实现文件拷贝
-
利用文件字节输入流,输出流实现文件的复制