合并内容格式不同的两个文件

题目描述:将文件a.txt中的单词与文件b.txt中的单词交替合并到文件c.txt中,a.txt中的单词用回车符分隔,b.txt中的单词用回车符或者空格分隔

思路分析:由于题目明确说明了文件a.txt与文件b.txt的分隔符有所不同,所以考虑新建一个文件类,该类描述文件,属性有单词、分隔符;然后在再建立一个合并文件的类,该类进行交替读写文件操作

文件描述类:

public class FileManager {
	String[] words = null;
	int pos = 0;
	
	public FileManager(String filename, char[] seperators) throws IOException{
		File file = new File(filename);
		FileReader fr = new FileReader(file);
		char[] buf = new char[(int)file.length()];
		int len = fr.read(buf);//将读取文件内容存放到buf中,同时返回字符数组长度
		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);
	}
	
	public String NextWord(){
		if(pos == words.length)
			return null;
		return words[pos++];
	}
}

文件合并操作类:

public class MergeFile {
	public static void main(String[] args) throws IOException {
		FileManager a = new FileManager("a.txt", new char[]{'\n'});
		FileManager b = new FileManager("b.txt", new char[]{'\n',' '});
		FileWriter c = new FileWriter("c.txt");
		String aWord = null;
		String bWord = null;
		while((aWord = a.NextWord()) != null){
			c.write(aWord + "\n");
			bWord = b.NextWord();
			if(bWord != null)
				c.write(bWord + "\n");
		}
		while((bWord = b.NextWord()) != null){
			c.write(bWord + "\n");
		}
		
		c.close();
	}
}



你可能感兴趣的:(regex,文件)