java io 编程题

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());
    			}
    		}
    	}


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值