编写一个程序,将 a.txt文件中的单词与b.txt文件中的单词交替合并到c.txt 文件中,a.txt文件中的单词用回车符分隔,b.txt文件中用回车或空格进行分隔
2015-07-14 14:45
645 查看
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语句这里的条件是比较优化的一点
相关文章推荐
- 程序员福利各大平台免费接口,非常适用
- LintCode Binary Tree Postorder Traversal 二叉树的后序遍历
- iOS耗电测试工具--batterydetective
- Hadoop:为什么RAID-0不行?
- 14.条件编译
- Oracle SGA优化
- php ob缓存
- 页面自动刷新的几种方式
- CDockablePane小技巧
- linux内核kallsyms机制分析
- 《算法的乐趣》前言中面试算法。
- ui开头的控件和ns开头的控件有什么区别iOS
- material颜色采样
- 黑白图像
- 【前端JS】radio 可单选可点击取消选中
- java 文件输出流覆盖问题
- 13.文件指针
- hdu 1533 Going Home(最小费用最大流)
- 计算之道 (淘汰赛车)
- Java基础-异常-throws Exception-抛声明