zoukankan      html  css  js  c++  java
  • 编写一个程序,将a.txt文件中的单词与b.txt文件中的单词交替合并到c.txt文件中

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

    package com.file;
    
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    
    public class ChangeFlie {
        FileManage a=new FileManage("a.txt",new char[]{'\n'});
        FileManage b=new FileManage("b.txt",new char[]{'\n',' '});
        FileWriter c=new FileWriter("c.txt");
        String aword=null;
        String bword=null;
        while((aword=a.nextwords())!=null){
            c.write(aword + "\n");
            bword = b.nextwords();
            if(bword != null)
                c.write(bword + "\n");
        }
        while((bword = b.nextwords()) != null){
            c.write(bword + "\n");
        }    
        c.close();
    }
    
    class FileManage{
        String[] words=null;
        int pos=0;
        public FileManage(String filename,char[] seperators) {
            File f=new File(filename);
            char[] buf=null;
            int len=0;
            try {   //必须是捕获异常,否则该类在初始化是会报错
                FileReader reader=new FileReader(f);
                buf = new char[(int)f.length()];
                len = reader.read(buf);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            String results=new String(buf,0,len);
            String regex=null;
            if(seperators.length>1){
                regex=""+seperators[0]+"|"+seperators[1];  //表示以空格或回车隔开单词
            }else{
                regex=""+seperators[0];   //表示以回车隔开单词
            }
            words=results.split(regex);   //按regex分隔字符串
        }
        public String nextwords(){
            if(pos==words.length){
                return null;
            }
            return words[pos++];
        }
    }
    }
  • 相关阅读:
    领会一些比较巧妙的算法
    操作系统os常识
    C++中的继承与虚函数各种概念
    我学shell程序的记录
    matlab:linux环境中将m文件编译成动态链接库
    struct内存对齐:gcc与VC的差别
    fedora中丢失或损坏fstab,无法启动,如何补救
    判断一个字符串中的字符是否都在另一个中出现
    linux下的不错的小软件:apvlv,zathura和vifm
    C语言中将结构体写入文件
  • 原文地址:https://www.cnblogs.com/xinxinjava/p/3076673.html
Copyright © 2011-2022 走看看