文件拷贝案例:
将一个已有文件(之前就创建好的)拷贝到另一个位置中。
代码:
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;
/**
* 文件拷贝:文件字节输入,输出流
* 1,创建源
* 2,选择流
* 3,操作(写出内容)
* 4,释放资源
* @author Administrator
*
*/
public class Copy {
public static void main(String[] args) {
//copy("p.jpg","pcopy.jpg");
copy("D:\\JavaCode\\IO_study02\\src\\Copy.java","copy.txt");
}
public static void copy(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,操作(写出)
//3,操作(分段读取)
byte[] flush=new byte[1024];//中间的缓冲容器
int len=-1;//接收长度初始化值
while((len=is.read(flush))!=-1) {//is.read(car)返回的是一个int值,当前读取字节的长度
os.write(flush, 0, len);
}
os.flush();
}catch(FileNotFoundException e){
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}finally {
//4,释放资源(分别关闭)(先打开的后关闭)
try {
if(null!=os) {
os.close();
}
}catch(IOException e) {
}
try {
if(null!=is) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
效果如下:
先看之前就创建好的文件(即该类的.Java文件)如下:
运行代码,效果图如下:
来源:CSDN
作者:zhe个芦苇
链接:https://blog.csdn.net/qiaoermeng/article/details/104267162