码迷,mamicode.com
首页 > 其他好文 > 详细

2014年去哪儿网笔试题--有两个文件context.txt和words.conf,请尝试将他们合并成为一段文字,并打印出来。

时间:2014-09-05 17:45:21      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   io   使用   java   ar   

有两个文件context.txt和words.conf,请尝试将他们合并成为一段文字,并打印出来。

这两个文件内容如下:

context.txt

“并不是每个人都需要$(qunar)自己的粮食,$(flight.1)每个人都需要做自己穿的$(flight.2),我们说着别人发明的$(hotel),使用别人发明的数学......我们一直在$(tuan)别人的成果。使用人类的已有经验和知识$(travel.1)来进行,是一件$(travel.2)的事情” 

 

word.conf

flight=也不是:衣服

qunar=种植

hotel=语言

tuan=使用

travel=发明创造:很了不起

参考博客:http://blog.csdn.net/wuwenxiang91322/article/details/11694051

对程序进行一点修改简化,思路还是没有变化。

主要涉及两方面操作,一方面就是文件的读取,也就是Java的IO操作;另一方面考察String的相关操作。

首先将两个文本读取,第一个文本context.txt可用FileReader 直接读取为String类型 ,第二个word.conf需要逐行读取采用的是BufferedReader 。

剩下就是word.conf读取内容转化为HashMap 用于下一步的查找替换,采用原作者的方式。

最后就是利用构建的HashMap对读取的context.txt内容进行替换。

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class TransferWord {
    public static void main(String[] args) throws IOException {
        String path = "D://word.conf";
        String contentPath = "D://context.txt";
        FileReader con = new FileReader(contentPath);
        FileReader word = new FileReader(path);
        // 读取主文件内容
        char[] cs = new char[500];
        int len = 0;
        String contextString = null;
        while ((len = con.read(cs)) != -1) {
            contextString = new String(cs, 0, len);
            System.out.println("文本内容:"+contextString);
        
        }
        con.close();
        // 配置文件注入hash
        BufferedReader br = new BufferedReader(word);
        String str;
        Map<String, String> map = new HashMap<String, String>();
        while ((str = br.readLine()) != null) {
            String pre = str.substring(0, str.indexOf("="));
            String sub = str.substring(str.indexOf("=") + 1, str.length());
            String[] arr = sub.split(":");
            if (arr.length != 1) {
                for (int i = 1; i <= arr.length; i++) {
                    map.put("$(" + pre + "." + i + ")", arr[i - 1].trim()); // 去掉首尾空格
                }
            } else {
                map.put("$(" + pre + ")", sub.trim());

            }
        }
        br.close();
        //进行替换操作
      Iterator iter=map.keySet().iterator();
      while(iter.hasNext()){
           String key=iter.next().toString();  
           String value=map.get(key);  
           if(contextString.contains(key)){  
               contextString=contextString.replace(key,value);
           }
      }
      //输出字符串
      System.out.println("新的文本内容:"+contextString);
    }
}

 

2014年去哪儿网笔试题--有两个文件context.txt和words.conf,请尝试将他们合并成为一段文字,并打印出来。

标签:style   blog   http   color   os   io   使用   java   ar   

原文地址:http://www.cnblogs.com/sunrunzhi/p/3958278.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!