Java 文件内容合并
2014-09-23 21:12
323 查看
最近看到一道面试题,题目是这样描述的:
编写一个程序,将a.txt文件中的单词与b.txt文件中的单词交替合并到c.txt文件中,a.txt文件中的单词用回车符分隔,b.txt文件中用回车或空格进行分隔
由于本人对于文件的读写并不熟悉,所以,亲自写了一遍,就算是笔记,当然,也方便大家学习交流.
编写一个程序,将a.txt文件中的单词与b.txt文件中的单词交替合并到c.txt文件中,a.txt文件中的单词用回车符分隔,b.txt文件中用回车或空格进行分隔
由于本人对于文件的读写并不熟悉,所以,亲自写了一遍,就算是笔记,当然,也方便大家学习交流.
package com.darren.test.file; import java.io.FileWriter; import java.io.IOException; public class MergeFileTest { public static void main(String[] args) { FileManager aFile = new FileManager("D:/a.txt", new char[]{'\n'}); FileManager bFile = new FileManager("D:/b.txt", new char[]{'\n',' '}); try { FileWriter writer = new FileWriter("D:/c.txt"); String aWord = null; String bWord = null; //注:使用两个while循环,防止b.txt的内容比a.txt的文件内容多 while((aWord = aFile.nextWord()) != null){ writer.write(aWord); writer.write("\n"); bWord = bFile.nextWord(); if(bWord != null){ writer.write(bWord); writer.write("\n"); } } while((bWord = bFile.nextWord()) != null){ writer.write(bWord); writer.write("\n"); } writer.close(); } catch (IOException e) { e.printStackTrace(); } } }
package com.darren.test.file; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class FileManager { /** * 单词数组 */ private String[] words; /** * 单词索引值 */ private int index = 0; /** * 文件管理器 * @param fileName 文件名 * @param separator 分隔符 */ public FileManager(String fileName, char[] separator){ String result = ""; try { File file = new File(fileName); FileReader reader = new FileReader(file); char[] buff = new char[(int) file.length()]; try { int length = reader.read(buff); result = new String(buff, 0, length); } catch (IOException e) { e.printStackTrace(); } String regex = null; int size = separator.length; //拼出正则表达式 for(int i = 0; i < size; i++){ regex = "" + separator[i] + "|"; } //去掉最后一位"|"符号 if(size > 0){ regex = regex.substring(0, regex.length() - 1); } words = result.split(regex); } catch (FileNotFoundException e) { e.printStackTrace(); } } /** * 读单词 * @return */ public String nextWord(){ if(index == words.length){ return null; }else{ return words[index++]; } } }
相关文章推荐
- 合并不同目录下,相同文件的内容(java实现)
- java实现合并2个文件中的内容到新文件中
- java编程之合并两个文件内容
- Java之将两个文件中的内容合并到一个文件中
- 将多个文本文件的内容合并为一个文件的Java实现
- 合并两个文件的内容:shell/java
- [Java] 利用xpdf库获取pdf文件的指定范围文本内容
- JAVA写的文件分割与文件合并程序
- JAVA写的文件分割与文件合并程序
- 用Java实现文件分割/合并操作
- java读取pdf文件内容
- java读取pdf文件内容
- java读取pdf文件内容
- 使用Apache POI和Java获得Excel文件内容,无须MS-Office ActiveX OLE
- [Java] 利用xpdf库获取pdf文件的指定范围文本内容
- java读取pdf文件内容
- 使用Java读取Excel文件内容
- Java读取文件内容并转换为字符串
- 如何用java实现在网页中保存html编辑器 编辑好的 html 文件?!(如blog里发文章的时候把要发表的内容以html文件的形式保存到服务器上?)
- Java 实现自动监听并更新配置文件内容