最近做了一个小练习,实现文件的复制,分为两种方法,一种是通过字符流实现复制和通过字节流实现复制
通过字符流实现文件的赋值
package com.cn.copy;
import java.io.FileReader;
import java.io.FileWriter;
public class copyByChar {
public static void main(String[] args) {
copyByChar("src/com/cn/copy/Copy.java","copyCopy.java");
}
public static void copyByChar(String srcName,String tagetName){
FileReader reader=null;
FileWriter writer=null;
try{
reader=new FileReader(srcName);
writer=new FileWriter(tagetName);
char[] aa=new char[1024];
int len=0;
while((len=reader.read(aa))!=-1){
writer.write(aa, 0, len);
}
}catch(Exception e){
e.printStackTrace();
}finally{
if(reader!=null){
try{
reader.close();
}catch(Exception e){
e.printStackTrace();
}finally{
if(writer!=null){
try{
writer.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
}
}
}
通过字节流实现文件的赋值
package com.cn.copy;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyByByte {
public static void main(String[] args) {
read(new File("aa.jpg"),new File("bb.jpg"));
}
public static void read(File srcFile,File tagetFile){
FileInputStream inStream=null;
FileOutputStream outStream=null;
try{
inStream=new FileInputStream(srcFile);
outStream=new FileOutputStream(tagetFile);
byte[] buff=new byte[1024];
int len=0;
while((len=inStream.read(buff))!=-1){
outStream.write(buff,0,len);
System.out.println("已经输入1024字节");
};
}catch(Exception e){
e.printStackTrace();
}finally{
try {
if(inStream!=null){
inStream.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try{
if(outStream!=null){
outStream.close();
}
}catch(Exception e){
e.printStackTrace();
}
}
}
}
}
1.获得目标资源
2.建立输入输出流
3.进行输入输出操作
4.关闭文件流
java7可以实现流的自动关闭
字符流和字节流的区别,字符流有个缓冲区,必须经过flush或者关闭流的操作才可以将数据写入到目标文件中,而字节流则没有,如果用字符流赋值图片之类的文件可能会出现字节丢失的现象,所以字符流适合复制文本文档文件,字节流适合复制图片之类的文件