`

FieldReader

阅读更多
package utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * 读取
 * <ul>
 * <li>xxx :xxxx</li>
 * </ul>
 * 格式的txt文档
 */
public class FieldReader
{
    private InputStream in;
    
    private Map<String, String> map = new HashMap<String, String>();
    
    public FieldReader(File file)
    {
        try
        {
            in = new FileInputStream(file);
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
    }
    
    public FieldReader(InputStream in)
    {
        this.in = in;
    }
    
    /** 获取键值对 */
    public Map<String, String> init()
    {
        read();
        return map;
    }
    
    private void read()
    {
        try
        {
            
            InputStreamReader reader = new InputStreamReader(in, "UTF-8");//当输入的文本已经知道编码格式时,直接使用
            BufferedReader buffer = new BufferedReader(reader);
            String s = "";
            String[] arr = null;
            while (s != null)
            {
                s = buffer.readLine();
                if (s == null || "".equals(s.trim()) || s.trim().startsWith("#"))
                    continue;
                arr = s.split("\\s*:\\s*");
                if (arr.length < 2)
                    continue;
                map.put(arr[0], arr[1]);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics