实现了处理流的字符流复制,处理流可以让程序效率更高,性能更好~~
package DemoBuffered;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class Demo9Buffered {
public static void main(String[] args) {
demo1();
}
public static void demo2(){
//1、建立关联
String srcPath = "D:/";
String destPath = "E:/";
String name = "a.txt";
File srcFile = new File(srcPath,name);
File destFile = new File(destPath,name);
//2、选择流
BufferedReader br = null;
BufferedWriter bw = null;
//3、传输
try {
br = new BufferedReader(new FileReader(srcFile));
bw = new BufferedWriter(new FileWriter(destFile));
String line = null;
while((line=br.readLine())!=null){
bw.write(line);
}
bw.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//4、关闭
try{
if(br!=null){
br.close();
}
if(bw!=null){
bw.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void demo1(){
String srcPath = "D:/";
String dest = "E:/";
String name = "a.txt";
//1、建立关联
File srcFile = new File(srcPath,name);
File destFile = new File(dest,name);
//2、选择流
InputStream is = null;
OutputStream os = null;
try {
//3、传输
is = new BufferedInputStream(new FileInputStream(srcFile));
os = new BufferedOutputStream(new FileOutputStream(destFile));
byte[] data = new byte[1024];
int len = 0;
while((len=is.read(data))!=-1){
os.write(data,0,len);
}
os.flush();
}catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//4、关闭
finally{
try {
if(is==null){
is.close();
}
if(os==null){
os.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
|
|