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

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 



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值