java讀取txt檔案的2中方法---並將內容(每一行以固定的字元分割切成2段)存到map中去

來源:互聯網
上載者:User

標籤: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中去

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.