5、使用IO流實現文件內容交替合併

編程題目:

5.編寫一個程序,將a.txt文件中的單詞與b.txt文件中的單詞交替合併到c.txt文件中,a.txt文件中的單詞用回車符分隔,b.txt文件中用回車或空格進行分隔。

示例代碼:

package program.stream.exercise05;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.Reader;
import java.io.Writer;

/**
 * 5.編寫一個程序,將a.txt文件中的單詞與b.txt文件中的單詞交替合併到c.txt文件中,
 *   a.txt文件中的單詞用回車符分隔,b.txt文件中用回車或空格進行分隔。
 */

public class FileCombine {
    public static void main(String[] args) throws Exception {

        //注意:在java等編程語言中,反斜槓\具有轉義的特殊作用,比如\t表示製表符,\n表示回車,
        //所以如果你想在字符串裏使用\的本意,就要用雙反斜槓,即\\才表示\
        //相對路徑(Eclipse默認生成文件位於項目名下即路徑寫到src處)
        FileManager a = new FileManager("src\\program\\stream\\exercise05\\a.txt",new char[]{'\n'});
        FileManager b = new FileManager("src\\program\\stream\\exercise05\\b.txt",new char[]{'\n',' '});    
        Writer c = new FileWriter("src\\program\\stream\\exercise05\\c.txt");
        //絕對路徑
        //FileWriter c = new FileWriter("D:\\Eclipse SE\\workspace\\Java Program\\src\\program\\stream\\exercise05\\c.txt");

        String aWord = null;
        String bWord = null;
        //a.txt和b.txt文件內容依次放入c.txt文件中
        while((aWord = a.nextWord()) != null ){
            c.write(aWord + "\n");//每個單詞用回車符分隔
            if((bWord = b.nextWord()) != null){
                c.write(bWord + "\n");
            }
        }

        System.out.println("寫入完成!");
        //關閉I/O流,不可少
        c.close();
    }

}

//文件管理類
class FileManager {

    private int index;//單詞數組下標
    private String[] words;//單詞數組

    public FileManager(String fileName,char[] seperators) throws Exception {

        File file = new File(fileName);
        Reader reader = new FileReader(file);
        char[] cs = new char[(int) file.length()];//定義一個字符數組,長度即是文件內容的長度
        int length = reader.read(cs);//有效字符數組長度
        String results = new String(cs,0,length);//將文件內容轉換成字符串

        String regex = null;//分隔符
        if(seperators.length > 1 ){
            regex = "" + seperators[0] + "|" + seperators[1];//將分隔符轉換成字符串,以便於分割
        }else{
            regex = "" + seperators[0];
        }
        words = results.split(regex);//將整個結果字符串分割成單詞數組

        reader.close();

    }

    //獲取下一個單詞
    public String nextWord(){
        if(index == words.length){
            return null;
        }
        return words[index++];
    }

}

結果顯示:

這裏寫圖片描述
這裏寫圖片描述
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章