示例代码:
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 org.junit.Test;
/**
* 1.流的分类:
* 按照数据流向的不同:输入流 输出流
* 按照处理数据的单位不同:字节流 (不能处理中文,一个中文由两个字节组成) 字符流(处理文本文件)
* 按照角色的不同:节点流(直接作用于文件) 处理流
* 2.IO体系:
* 抽象基类 节点流 缓冲流(处理流的一种,可以提高文件处理的效率)
* InputStream FileInputStream BufferedInputStream
* OutputStream FileOutputStream BufferedOutputStream (flush())
* Reader FileReader BufferedReader (readLine())
* Writer FileWriter BufferedWriter (flush())
*
*/
public class TestBuffered {
//使用BufferedInputStream和BufferedOutputStream实现非文本文件的复制
@Test
public void test1() {
//3.将创建的具体的节点流对象作为形参传递给缓冲流的构造器
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
//1.提供读入和写出的文件
File file1 = new File("1.jpg");
File file2 = new File("2.jpg");
//2.先创建相应的节点流:FileInputStream和FileOutputStream
FileInputStream fis = new FileInputStream(file1);
FileOutputStream fos = new FileOutputStream(file2);
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(fos);
//4.具体的实现文件复制的操作
byte[] b = new byte[1024];
int len;
while((len = bis.read(b)) != -1) {
bos.write(b, 0, len);
bos.flush();//最后一次写缓存可能存不满,把缓存清空
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(bos != null) {
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(bis != null) {
try {
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
@Test
public void test2() {
BufferedReader br = null;
BufferedWriter bw = null;
try {
File file = new File("hello.txt");
File newfile = new File("newfile.txt");
FileReader fr = new FileReader(file);
FileWriter fw = new FileWriter(newfile);
br = new BufferedReader(fr);
bw = new BufferedWriter(fw);
/*
* 输出到控制台
*/
//方法一:
/*char[] c = new char[1024];
int len;
while((len = br.read(c)) != -1) {
System.out.println(new String(c, 0, len));
}*/
//方法二:
/*String str;
while((str = br.readLine()) != null) {
System.out.println(str);
}*/
/*
* 输出到文件
*/
String str2;
while((str2 = br.readLine()) != null) {
bw.write(str2);
bw.newLine();//换行,也可以str2+"\n"
bw.flush();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}