java读写文件

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


程序如下:

package com.read;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

public class MainTest {

public static void main(String[] args) throws Exception{
File f1 = new File("src/com/read/a.txt");
File f2 = new File("src/com/read/b.txt");

String str1 = readFile(f1);
String str2 = readFile(f2);
String [] strArray1 = str1.split(" ");
String [] strArray2 = str2.split("-| ");

FileWriter c = new FileWriter("src/com/read/c.txt");

int len1 = strArray1.length;
int len2 = strArray2.length;

boolean bool = len1>len2?true:false;
int i,j;
if(bool){
for(i=0;i<len2;i++){
c.write(strArray1[i]+" ");
c.write(strArray2[i]+" ");
}
for(int k =i;k<len1;k++){
c.write(strArray1[k]+" ");
}
}else{
for(j=0;j<len1;j++){
c.write(strArray1[j]+" ");
c.write(strArray2[j]+" ");
}
for(int k = j;k<len2;k++){
c.write(strArray2[k]+" ");
}
}
c.close();
}

public static String readFile(File file){
StringBuffer stringBuffer = new StringBuffer("");
BufferedReader reader = null;
try{
reader = new BufferedReader(new FileReader(file));
String tempStr = "";
while((tempStr=reader.readLine())!=null){
stringBuffer.append(tempStr);
}
}catch (Exception e) {
e.printStackTrace();
}
return stringBuffer.toString();
}
}



a.txt文件内容:

1 2 3 4 55 67

b.txt文件内容:

q w-2 3-3 4rt 5-y


输出的c.txt文件内容为:

1 q 2 w 3 2 4 3 55 3 67 4rt 5 y
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值