1、编写一个程序,将a.txt文件中的单词与b.txt文件中的单词交替合并到c.txt文件中,a.txt文件中的单词用回车符分隔,b.txt文件中用回车或空格进行分隔。
package com.test;import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;public class TestCopyChar {public static void main(String[] args) {testCopy();}/*** 编写一个程序,将a.txt文件中的单词与b.txt文件中的单词交替合并到c.txt文件中,a.txt文件中的单词用回车符分隔,b.txt文件中用回车或空格进行分隔。*/public static void testCopy() {File file = new File("./demo/a.txt");FileReader fr = null;try {fr = new FileReader(file);} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}File file1 = new File("./demo/b.txt");FileReader fr1 = null;try {fr1 = new FileReader(file1);} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}FileWriter fw = null;try {fw = new FileWriter("./demo/c.txt");} catch (IOException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}char[] buf = new char[(int) file.length()];char[] bufb = new char[(int) file1.length()];int len = 0;int len1 = 0;try {len = fr.read(buf);len1 = fr1.read(bufb);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}String aStr = new String(buf,0,len);String bStr = new String(bufb,0,len1);System.out.println(aStr);System.out.println(bStr);System.out.println("***********");String[] aArr = aStr.split("[\n]");String[] bArr = bStr.split("[ \n]");System.out.println(Arrays.toString(aArr));System.out.println(Arrays.toString(bArr));if (aArr.length > bArr.length) {for (int i = 0; i < aArr.length; i++) {try {fw.write(aArr[i] + "\n");if ((i < bArr.length) && (null != bArr[i])) {fw.write(bArr[i] + "\n");}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}else {for (int i = 0; i < bArr.length; i++) {try {fw.write(bArr[i] + "\n");if ((i < aArr.length) && (null != aArr[i])) {fw.write(aArr[i] + "\n");}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}try {fr.close();fr1.close();fw.close();//fw.flush(); close()有flush()的作用,将输出流中的字符写入到文件中} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}