首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >编写一个程序,将 a.txt文件中的单词与b.txt文件中的单词交替合并到c.txt 文件中,a.txt文件中的单词用回车符分隔,b.txt文件中用回车或空格进行分隔

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

作者头像
粲然
发布2022-08-02 14:53:11
发布2022-08-02 14:53:11
3.2K0
举报
文章被收录于专栏:工程师的分享工程师的分享
代码语言:javascript
复制
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class newManagerFile {
	String words[];
	int pos = 0;

	public newManagerFile(String fileName, char spilt[]) throws Exception {
		File file = new File(fileName);
		FileReader fr = new FileReader(file);
		char buf[] = new char[(int) file.length()];
		int len = fr.read(buf);
		String bufString = new String(buf, 0, len);
		StringBuffer temp = new StringBuffer("");
		temp.append(spilt[0]);
		if (spilt.length > 1) {
			int posl = 2;
			while (posl <= spilt.length) {
				temp.append("|");
				temp.append(spilt[posl - 1]);
				posl++;
			}
		}
		String bs = temp.toString();
		words = bufString.split(bs);
	}

	public String nextWord() {
		if (pos == words.length) {
			return null;
		} else {
			return words[pos++];
		}

	}

	public static void main(String[] args) throws Exception {
		newManagerFile a = new newManagerFile("G:\\a.txt", new char[] { '\n' });
		newManagerFile b = new newManagerFile("G:\\b.txt", new char[] { '\n',
				' ' });
		FileWriter c = new FileWriter("G:\\c.txt");
		String aWord = null;
		String bWord = null;
		while ((aWord = a.nextWord()) != null) {
			c.write(aWord);
			bWord = b.nextWord();
			if (bWord != null) {
				c.write(bWord);
			}
		}
		if (bWord != null) {
			c.write(bWord);
		}
		c.close();
		System.out.println("finish");
	}
}

主要对文件读写的考察,自己一开始编写的可读性不好,借鉴了一下已有的代码进行了优化,这里建议不要过多使用string而是用stringbuffer,while语句这里的条件是比较优化的一点

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2015-07-14,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档