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

package IO;

import java.io.*;

public class test {
	
	public  void connectWords(File file1, File file2, File file3)throws IOException
	{
		String[] str1 = split(file1, "
");
		String[] str2 = split(file2, "
"+"|"+" ");
		try(FileWriter fw = new FileWriter(file3))
		{	
			int index = 0;
			while(index != str1.length||index != str2.length)
			{
				if(index < str1.length)
					fw.write(str1[index]);
				if(index < str2.length)
					fw.write(str2[index]);
				index ++;
			}
		}
	}
	
	public String[] split(File f, String regex)throws IOException
	{
		try(FileReader fr = new FileReader(f))
		{
			char[] cbuf = new char[(int)f.length()];
			int hasRead = fr.read(cbuf);
			String str = new String(cbuf, 0, hasRead);
			String[] strArr = str.split(regex);
			return strArr;
		}
	}
	public static void main(String[] args) throws IOException
	{
		File f1 = new File("./a.txt");
		File f2 = new File("./b.txt");
		File f3 = new File("./c.txt");
		test t = new test();
		t.connectWords(f1, f2, f3);
	}
	
}
原文地址:https://www.cnblogs.com/masterlibin/p/5646798.html