IO技术实现文件的拷贝
步骤:
1:创建一个FileInputStream对象用于读取指定文件,
同时可以使用BufferedInputStream对象对FileInputStream进行包装
2:同时创建ByteArrayOutputStream ,用于保存读取到的数据
3:创建BufferedOutputStream 对象,用于一次将全部数据写入到指定目录中
4:关闭流
package com.haikang.io_;
import java.io.*;
/**
* @author: 海康
* @version: 1.0
*/
public class FileCopy {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("e:\\rose.jpg");
BufferedInputStream bis = new BufferedInputStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] bytes = new byte[1024*8];
int length = 0;
while ((length=bis.read(bytes))!=-1){
baos.write(bytes,0,length);
}
BufferedOutputStream oos = new BufferedOutputStream(new FileOutputStream("src\\myRose.jpg"));
oos.write(baos.toByteArray());
oos.flush();
// 关闭流
if (oos!=null){
oos.close();
}
if (baos!=null){
baos.close();
}
if (bis!=null){
bis.close();
}
System.out.println("文件拷贝成功!");
}
}
方式二:
package IO_.writer_;
import java.io.*;
/**
* @author: 海康
* @version: 1.0
*/
public class BufferedCopy2 {
public static void main(String[] args) {
String srcCopy = "e:\\rose.jpg";
String doesCopy = "d:\\myRose.jpg";
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(srcCopy));
bos = new BufferedOutputStream(new FileOutputStream(doesCopy));
int length = 0;
byte[] ch = new byte[1024*8];
while ((length = bis.read(ch))!=-1){
bos.write(ch,0,length);
}
System.out.println("拷贝完成!!!");
} catch (IOException e) {
e.printStackTrace();
}finally {
// 在使用完流一定要关闭流,在包装流关闭外层流即可
if (bis != null){
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bos != null){
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
方式三:使用File类中length方法,一次性将全部数据读取到一个数据中,不适用读取较大文件
package com.haikang.io_;
import java.io.*;
/**
* @author: 海康
* @version: 1.0
*/
public class FileCopy {
public static void main(String[] args) throws IOException {
File file = new File("e:\\rose.jpg");
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
long length = file.length();
byte[] bytes = new byte[(int) length];
bis.read(bytes);
BufferedOutputStream oos = new BufferedOutputStream(new FileOutputStream("src\\myRose2.jpg"));
oos.write(bytes);
oos.flush();
// 关闭流
if (oos!=null){
oos.close();
}
if (bis!=null){
bis.close();
}
System.out.println("文件拷贝成功!");
}
}