黑马程序员技术交流社区

标题: 文件复制请高手解决 [打印本页]

作者: 超级小小二郎    时间: 2013-7-3 22:23
标题: 文件复制请高手解决
本帖最后由 杜光 于 2013-7-5 07:30 编辑

编写一个程序,将a.txt文件中的单词与b.txt文件中的单词交替合并到c.txt文件中,a.txt文件中的单词用回车符分隔,b.txt文件中用回车或空格进行分隔。
作者: 王靖远    时间: 2013-7-3 22:35
交替合并是存一个a里的单词再存一个b里的单词再存a里的单词这样循环来存?
作者: hadexs    时间: 2013-7-3 23:15
  1. package cn.itcast;

  2. import java.io.File;

  3. import java.io.FileReader;

  4. import java.io.FileWriter;



  5. public class MainClass{

  6.       public static void main(String[] args) throws Exception{

  7.             FileManager a = new FileManager("a.txt",new char[]{'\n'});

  8.             FileManager b = new FileManager("b.txt",new char[]{'\n',' '});         

  9.             FileWriter c = new FileWriter("c.txt");

  10.             String aWord = null;

  11.             String bWord = null;

  12.             while((aWord = a.nextWord()) !=null ){

  13.                   c.write(aWord + "\n");

  14.                   bWord = b.nextWord();

  15.                   if(bWord != null)

  16.                         c.write(bWord + "\n");

  17.             }

  18.             

  19.             while((bWord = b.nextWord()) != null){

  20.                   c.write(bWord + "\n");

  21.             }     

  22.             c.close();

  23.       }

  24.       

  25. }



  26. class FileManager{



  27.       String[] words = null;

  28.       int pos = 0;

  29.       public FileManager(String filename,char[] seperators) throws Exception{

  30.             File f = new File(filename);

  31.             FileReader reader = new FileReader(f);

  32.             char[] buf = new char[(int)f.length()];

  33.             int len = reader.read(buf);

  34.             String results = new String(buf,0,len);

  35.             String regex = null;

  36.             if(seperators.length >1 ){

  37.                   regex = "" + seperators[0] + "|" + seperators[1];

  38.             }else{

  39.                   regex = "" + seperators[0];

  40.             }

  41.             words = results.split(regex);

  42.       }

  43.       

  44.       public String nextWord(){

  45.             if(pos == words.length)

  46.                   return null;

  47.             return words[pos++];

  48.       }



  49. }
复制代码

作者: 王靖远    时间: 2013-7-3 23:40
hadexs 发表于 2013-7-3 23:15

:handshake给力
作者: 张承富    时间: 2013-7-4 00:47
给点注释吧,看着费劲
作者: 杨兴庭    时间: 2013-7-4 07:36
为了更好的维护论坛的学习氛围,如果您的的问题“已经解决”请即时将帖子状态改成“已解决”

-------------------坚持学习,黑马因你而精彩---------------




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2