- import java.io.BufferedReader;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.PrintStream;
- import java.io.SequenceInputStream;
- import java.util.Enumeration;
- import java.util.Vector;
- /**
- * 示例:用合并流将part1.txt,part2.txt,part3.txt三个文件
- * 打印到total.txt文件中
- * @author lt
- */
- public class SequeceInputStreamDemo {
- //获取Vector对象,传入的参数个数是可变长度的,Vector中可以添加任意多个元素
- public static Vector<InputStream> getVector(String... values) throws FileNotFoundException{
- Vector<InputStream> v = new Vector<InputStream>();
- for(int i = 0;i < values.length;i++){
- try {
- v.add(new FileInputStream(values[i]));
- } catch (FileNotFoundException e) {
- throw e;
- }
- }
- return v;
- }
- //打印三个文件中的内容到一个文件中去
- public static void printToTotal(Vector<InputStream> v) throws IOException{
- Enumeration<InputStream> e = v.elements();
- //输入流是一个合并流
- BufferedReader br = new BufferedReader(new InputStreamReader(new SequenceInputStream(e)));
- PrintStream ps = new PrintStream(new FileOutputStream("total.txt"),true);
- String line = null;
- try {
- while((line = br.readLine()) != null){
- ps.println(line);
- }
- } catch (IOException e1) {
- throw e1;
- }
- }
- public static void main(String[] args) {
- String path1 = "part1.txt";
- String path2 = "part2.txt";
- String path3 = "part3.txt";
- Vector<InputStream> v = null;
- try {
- v = getVector(path1,path2,path3);
- printToTotal(v);
- } catch (FileNotFoundException e) {
- System.out.println("文件路径有误!");
- } catch (IOException e) {
- System.out.println("目标文件无法创建!");
- }
- }
- }
复制代码 第一个文件中是"aaa",第二个文件中"bbb","第三个文件中"ccc",我想把他们合并在一个文件,但是我用PrintOutputStream打印流打印出来的结果是"aaabbbccc",连在一起的没换行。这是为什么呢?打印流的println方法不是自动换行吗?
|