字节方式copy
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.junit.Test;
public class ByteStream {
@Test
public void byteCopy(){
File file=null;
File file2= null;
InputStream iStream=null;
OutputStream oStream=null;
try {
file = new File("F:\\tupian.jpg");
file2 = new File("E:\\英雄时刻\\123.jpg");
iStream = new FileInputStream(file);
oStream = new FileOutputStream(file2);
byte[] b = new byte[512];
int len= 0;
while((len=iStream.read(b))!=-1){
oStream.write(b);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
oStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
iStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
buffered缓冲区方式
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.junit.Test;
public class BufStream {
@Test
public void bufCopy(){
File file=null;
File file2 = null;
InputStream iStream=null;
OutputStream oStream = null;
BufferedInputStream bufiStream=null;
BufferedOutputStream bufoStream=null;
try {
file=new File("e:\\算法与分析\\楷书编程与编码规范.rar");
file2=new File("f:\\编码规范.rar");
iStream=new FileInputStream(file);
oStream=new FileOutputStream(file2);
bufiStream=new BufferedInputStream(iStream);
bufoStream=new BufferedOutputStream(oStream);
byte[] buf=new byte[512];
int len=0;
while((len=bufiStream.read(buf))!=-1){
bufoStream.write(buf);
bufoStream.flush();
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
bufoStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
bufiStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
char字符文本的copy
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import org.junit.Test;
public class CharStream {
@Test
public void charCopy(){//实现两个文件的copy
File file = null;//源文件
File file2 = null;//目标文件
FileReader fReader = null;
FileWriter fWriter = null;
try{
file = new File("F:\\hello");
file2 = new File("F:\\temp.txt");
fReader = new FileReader(file);
fWriter = new FileWriter(file2);
char[] c = new char[50];
int len= 0;
while((len=fReader.read(c))!=-1){
//把读到的内容写到目标文件中
fWriter.write(c, 0, len);
fWriter.flush();
}
}catch(Exception e){
e.printStackTrace();
}finally {
try {
fWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}