之前学IO流的时候列举了常见的IO流组合形式,笔者这里就不赘述了。直接上代码。
IO流中常用的组合方式
1.第一种字节流
的FileInputStream和FileOutputStream中组合
在程序中体现
公共类FileCopy {
public static void main(String [] args){
//第一步声明流
FileInputStream fis = null;
FileOutputStream fos = null;
尝试{
//第二步创建流的对象
fis = new FileInputStream(“”);
fos =新FileOutputSteam(“”);
//第三步读取流
byte [] buff = new byte [256];
int length = 0;
而(!(length= fis.read(buff))= - 1){
System.out.println(new String(buff,0,length)); //在控制台先打印出来相关信息
fos.write(buff,0,length);
}
catch(FileNotFoundException e){
e.printStackTrace();
最后{
//第四步关闭流
尝试{
if(fis!= null)fis.close();
if(fos!= null)fos.close();
catch(IOException e){
e.printStackTrace();
}
}
}
}
2.第二种
字符流FileReader和FileWriter组合
公共类FileCopy2 {
public static void main(String [] args){
//第一步声明流
FileReader fr = null;
FileWriter fw = null;
尝试{
//第二步创建流的对象
fr = new FileReader(“”);
fw = new FileWriter(“”);
//第三步读取流
char [] buff = new char [256];
int length = 0;
while(!(length= fr.read(buff))= - 1){
System.out.println(new String(buff,0,length));
fw.writer(buff,0,length);
}
catch(Exception e){
e.printStackTrace();
最后{
//第四步关闭流
尝试{
如果(fr!= null)fr.close();
if(fw!= null)fw.close();
catch(IOException e){
e.printStackTrace();
}
}
}
}
3.第三种
BufferedReader和PrintWriter组合(常用)
公共类FileCopy3 {
public static void main(String [] args){
//第一步声明流
BufferedReader br = null;
PrintWriterReader pw = null;
尝试{
//第二步创建流的对象
br = new BufferedReader(new FileReader(“”));
pw = new PrintReader(“”);
//第三步从缓冲区中读取流
String line = null;
while((line= br.readLine())!= NULL){
System.out.println(line);
pw.println(line);
}
pw.flush(); //刷新缓冲区中的字符流,缓冲区的(字节流或字符流)一定要刷新出来
//正常的流中的close()方法中已经使用了齐平()方法,没有必要再次刷新
catch(Exception e){
e.printStackTrace();
}最后{
尝试{
//第四步关闭流
if(br!= null)br.close();
if(pw!= null)pw.close();
catch(IOException e){
e.printStackTrace();
}
}
}
}
4.第四种
字节缓存流(了解使用)
的BufferedInputStream和的BufferedOutputStream
5.第五种
转换流(了解)
InputStreamReader将字节流转换成字符流
OutputStreamReader将字符流转换为字节流
6.第六种
管道流(了解)
PipedInputStream和PipedOutputStream
以上列举了常见的IO流组合形式,其中第三种最为实用。代码的话笔者用了最简单的方式来实现了下,欢迎吐槽。