#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; }
