/*
* 合併(序列)流
*/
package Test2;
import java.io.*;
public class Demo23_11 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Demo23_11 d = new Demo23_11();
}
public Demo23_11()
{
//聲明兩個文件讀入流
FileInputStream in1 = null,in2 = null;
//聲明一個合併流
SequenceInputStream s = null;
FileOutputStream out = null;
//1.txt和2.txt必須事先存在並已經寫入
File input1 = new File("D:" + File.separator + "1.txt");
File input2 = new File("D:" + File.separator + "2.txt");
File output = new File("D:" + File.separator + "12.txt");
try {
in1 = new FileInputStream(input1);
in2 = new FileInputStream(input2);
//將兩個輸入流合併爲一個輸出流
s = new SequenceInputStream(in1, in2);
out = new FileOutputStream(output);
//read在讀到流的結尾處返回-1
int c;
while((c = s.read()) != -1)
{
out.write(c);
}
System.out.println("ok");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
//如果說這四個還沒有讀取完畢也要關閉,防止異常
try {
in1.close();
in2.close();
s.close();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// if(in1 != null)
// try {
// in1.close();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// if(in2 != null)
// try {
// in2.close();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// if(s != null)
// try {
// s.close();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// if(out != null)
// try {
// out.close();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
}
}
}
合併(序列)流
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.