java读取txt文件的2中方法---并将内容(每一行以固定的字符分割切成2段)存到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;

    }

 

转载于:https://www.cnblogs.com/lancexu/p/9405639.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值