java io 编程题

来源:互联网 发布:九之濑遥cos淘宝全套 编辑:程序博客网 时间:2024/06/10 04:22

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

class FileManager{    String[] words=null;    public FileManager(String filename,char[] seperator) throws IOException{        File file=new File(filename);        InputStream is=new FileInputStream(file);        byte[] b=new byte[(int)file.length()];        is.read(b);        is.close();        String regx="";        if(seperator.length>1)            regx+=seperator[0]+"|"+seperator[1];        else            regx+=seperator[0];        words=new String(b).split(regx);    }

   public static void Test7()throws IOException{        FileManager a=new FileManager("a.txt",new char[]{'\n'});        FileManager b=new FileManager("b.txt",new char[]{'\n',' '});        File file=new File("c.txt");        Writer w=new FileWriter(file);        int len1=a.words.length;        int len2=b.words.length;        int i;        if(len1>len2){            for(i=0;i<len2;i++){                w.write(a.words[i]+"\n");                w.write(b.words[i]+"\n");            }            while(i<len1){                w.write(a.words[i]+"\n");                i++;            }        }else{            for(i=0;i<len1;i++){                w.write(a.words[i]+"\n");                w.write(b.words[i]+"\n");            }            while(i<len2){                w.write(b.words[i]+"\n");                i++;            }        }        w.close();        Reader r=new FileReader(file);        char[] ch=new char[1024];        r.read(ch);        r.close();        System.out.println(new String(ch));    }

2.给定一个文件和一个字符串,判断文件是否包含该字符串,如果包含,请打印包含该字符串的行号及该行的全部内容

  public static void Test8(String filename,String str) throws IOException{    int lineNum=0;    Map<Integer,String> map=new HashMap<Integer,String>();        File file=new File(filename);    BufferedReader br=new BufferedReader(new FileReader(file));    while(br.readLine()!=null){    String tmp=br.readLine();    if(tmp.contains(str))    map.put(lineNum, tmp);    lineNum++;    }    br.close();    if(map.isEmpty())    System.out.println("该文件不包含该字符串");    else{    Iterator<Entry<Integer,String>> iterator=map.entrySet().iterator();    while(iterator.hasNext()){    Entry<Integer,String> entry=iterator.next();    System.out.println("行号:"+entry.getKey()+"该行内容:"+entry.getValue());    }    }    }


原创粉丝点击