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 

你可能感兴趣的:(java)