编写一个程序,将a.txt文件中的单词与b.txt文件中的单词交替合并到c.txt文件中

编写一个程序,将a.txt文件中的单词与b.txt文件中的单词交替合并到c.txt文件中,a.txt文件中的单词用回车符分隔,b.txt文件中用回车或空格进行分隔。

 

package com.file;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class ChangeFlie {
    FileManage a=new FileManage("a.txt",new char[]{'\n'});
    FileManage b=new FileManage("b.txt",new char[]{'\n',' '});
    FileWriter c=new FileWriter("c.txt");
    String aword=null;
    String bword=null;
    while((aword=a.nextwords())!=null){
        c.write(aword + "\n");
        bword = b.nextwords();
        if(bword != null)
            c.write(bword + "\n");
    }
    while((bword = b.nextwords()) != null){
        c.write(bword + "\n");
    }    
    c.close();
}

class FileManage{
    String[] words=null;
    int pos=0;
    public FileManage(String filename,char[] seperators) {
        File f=new File(filename);
        char[] buf=null;
        int len=0;
        try {   //必须是捕获异常,否则该类在初始化是会报错
            FileReader reader=new FileReader(f);
            buf = new char[(int)f.length()];
            len = reader.read(buf);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String results=new String(buf,0,len);
        String regex=null;
        if(seperators.length>1){
            regex=""+seperators[0]+"|"+seperators[1];  //表示以空格或回车隔开单词
        }else{
            regex=""+seperators[0];   //表示以回车隔开单词
        }
        words=results.split(regex);   //按regex分隔字符串
    }
    public String nextwords(){
        if(pos==words.length){
            return null;
        }
        return words[pos++];
    }
}
}

 

 

 

posted @ 2013-05-13 22:37  欣欣家园  阅读(588)  评论(1编辑  收藏  举报