码迷,mamicode.com
首页 > 编程语言 > 详细

java读取txt文件的2中方法---并将内容(每一行以固定的字符分割切成2段)存到map中去

时间:2018-08-02 11:15:01      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:add   param   pat   ada   style   ram   buffere   map   功能   

#java读取txt文件的第一种方法

/**
     * 方法:readTxt
     * 功能:读取txt文件并把txt文件的内容---每一行作为一个字符串加入到List中去
     * 参数:txt文件的地址
     * 返回:Map
     * @param file
     * @return
     * @throws IOException
     */
    public static Map<String, String> readTxt(String file) throws IOException {

        Map<String, String> tempMap = new HashMap<String, String>();
        List<String> allLines = Files.readAllLines(Paths.get(file));
        
        //以下为我截取文件内容,一行分成2段,第一段设置为Map的Key,第二段设置为Map的Value
        for (String line : allLines) {
            if (line != "") {
                String[] temp = line.split(" J::  ");

                if (temp.length == 2) {
                    tempMap.put(temp[0], temp[1]);
                }
            }
        }

        return tempMap;
    }

#读取txt文件的第二种方法

    public Map<String, String> read() throws Exception{


//      List<String> allLines = Files.readAllLines(Paths.get(File));
        /*
        通常,由读取器做出的每个读取请求将引起对底层字符或字节流的相应读取请求。
        因此,建议将BufferedReader包装在其read()操作可能昂贵的读取器上,
        例如FileReaders和InputStreamReaders
         */
        FileReader fileReader = new FileReader(File);
        BufferedReader bufferedReader = new BufferedReader(fileReader);

        Map<String,String> tempMap = new HashMap<String,String>();

        while((lines = bufferedReader.readLine()) != null)
        {
                list.add(lines);
        }
        bufferedReader.close();

        //以下为我切割的规则,一行切成2段,第一段设置为Map的Key,第二段设置为Map的Value
        for(String singleList : list)
        {
            if(singleList != "")
            {
                String[] temp = singleList.split( "J::  ");

                if(temp.length == 2)
                {
                    tempMap.put(temp[0],temp[1]);
                }
            }

        }
        return tempMap;

    }

 

java读取txt文件的2中方法---并将内容(每一行以固定的字符分割切成2段)存到map中去

标签:add   param   pat   ada   style   ram   buffere   map   功能   

原文地址:https://www.cnblogs.com/lancexu/p/9405639.html

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