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