算法与编程--1

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 block
			e.printStackTrace();
		}
		
		File file1 = new File("./demo/b.txt");
		FileReader fr1 = null;
		try {
			fr1 = new FileReader(file1);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		FileWriter fw = null;
		try {
			fw = new FileWriter("./demo/c.txt");
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.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 block
			e.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 block
					e.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 block
					e.printStackTrace();
				}
			}
		}
		try {
			fr.close();
			fr1.close();
			fw.close();//fw.flush(); close()有flush()的作用,将输出流中的字符写入到文件中
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
}

  

转载于:https://www.cnblogs.com/hblthink/p/8343460.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值