zoukankan      html  css  js  c++  java
  • 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;
    
        }
  • 相关阅读:
    H5页面与ios交互返回上一级
    url传中文参数乱码问题
    获取除当前元素外的所有类名相同的元素
    vue根据id删除某一行
    非对称加密算法
    Linux下nc命来实现文件传输
    linux下挂载第二块硬盘
    libcprops
    android开发环境安装记录
    MD(d)、MT(d)编译选项的区别
  • 原文地址:https://www.cnblogs.com/lancexu/p/9405639.html
Copyright © 2011-2022 走看看