a.txt
hello
world
my
friend
jack
tom
b.txt
house home desk
Alice
pig
cat
wind
package com.hbut.test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
/**
* 1、编写一个程序,将a.txt文件中的单词与b.txt文件中的单词交替合并到c.txt文件中,a.txt文件中的单词用回车符分隔,b.txt文件中用回车或空格进行分隔
*
*/
public class PutWordsToC {
public static void main(String[] args) throws IOException {
File fileA= new File("a.txt");
Reader readerA = new FileReader(fileA);
//创建可以一次读取一行的输入流
BufferedReader a = new BufferedReader(readerA); //一次读取一行,结束符为null
File fileB= new File("b.txt");
Reader readerB = new FileReader(fileB);
BufferedReader b = new BufferedReader(readerB); //一次读取一行,结束符为null
String str1=a.readLine();
//用于单词的计数
int wordsA=0;
//缓冲区,可以把读取的单词存进去
StringBuffer bufA= new StringBuffer();
while(str1!=null){
System.out.println(str1);
str1=a.readLine();
wordsA++;
if(str1!=null)
bufA.append(str1);
bufA.append(" ");
}
System.out.println("a.txt单词数:"+wordsA);
System.out.println("-------------------------");
String str2=b.readLine();
int wordsB=0;
StringBuffer bufB= new StringBuffer();
while(str2!=null){
String[] st = str2.split(" "); //例如读取的一行为:house home desk
wordsB+=st.length;
for(String i :st){
bufB.append(i); //把切割后的字符放到b的缓冲区
bufB.append(" ");
}
System.out.println(str2);
str2=b.readLine();
}
System.out.println("b.txt单词数:"+wordsB);
System.out.println("A文件:"+bufA);
System.out.println("B文件:"+bufB);
String strA=bufA.toString(); //转为字符串
String strB=bufB.toString();
String []A=strA.split(" ");
String []B=strB.split(" ");
int total=wordsA+wordsB;
String [] result=new String [total-1]; //创建一个字符串数组,可以容纳a.txt以及b.txt的单词的总数
if(wordsA<wordsB)//只做了a文件的单词数比b的少的,后面加个else就可以了
{
int j=0;
for(int i=0;i<wordsB;i++)
{
result[j]=B[i];
j++;
if(i<A.length)
{
result[j]=A[i];
j++;
}
}
}
String content ="";
for(String x:result){
content+=x+" "; //把字符数组的内容转为字符串
}
System.out.println("content:"+content);
File fileC = new File("c.txt");
Writer w = new FileWriter(fileC);
w.write(content); //把字符串写到c.txt里去
w.close(); //一定要关闭,不然无法成功的
}
}
c.txt内容为:house world home my desk friend Alice jack pig tom cat wind