编写程序整合文件中内容

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

package com.alex.test;

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

public class MainClass {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		FileManager aFile = new FileManager("C:\\a.txt");
		String[] aStrs=aFile.getContentStringArray(new char[]{'\n'});
		FileManager bFile = new FileManager("C:\\b.txt");
		String[] bStrs=bFile.getContentStringArray(new char[]{'\n',' '});
		FileWriter cFile=null;
		try {
			cFile = new FileWriter(new File("C:\\c.txt"));
		} catch (IOException e) {
			e.printStackTrace();
		}
		StringBuilder consolidateWords=new StringBuilder("");
		String aWord=null;
		String bWord=null;
		while((aWord=aFile.getNextWord())!=null){			
			consolidateWords.append(aWord).append("\n");
			if((bWord=bFile.getNextWord())!=null){
				consolidateWords.append(bWord).append("\n");
			}		
		}
		bWord=null;
		while((bWord=bFile.getNextWord())!=null){
			consolidateWords.append(bWord).append("\n");
		}
		try {
			cFile.write(consolidateWords.toString());
			cFile.flush();
			cFile.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

package com.alex.test;

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

public class FileManager {
	private String[] words ;
	private String filePath;
	private int index=0;
	public FileManager(String filePath){
		this.filePath=filePath;
	}
	
	public String[] getContentStringArray(char[] regexConditions){
		File file = null ;
		FileReader fr = null;
		int len=0;
		try {
			file = new File(filePath);
			fr = new FileReader(file);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		char[] cbuf = new char[(int)file.length()];
		try {
			len = fr.read(cbuf);		
		} catch (IOException e) {
			e.printStackTrace();
		}
		String consolidateContent = new String(cbuf,0,len);
		StringBuilder regex = new StringBuilder("");
		for(char regexCondition:regexConditions){
			regex.append(regexCondition).append("|");
		}
		regex.deleteCharAt(regex.length()-1);
		words = consolidateContent.split(regex.toString());
		return words;
	}
	
	public String getNextWord(){
		if(index==words.length){
			return null;
		}
		return words[index++];
	}
	
}


你可能感兴趣的:(c,String,File,null,Class,regex)