java讀取.txt檔案工具類FileUtiles
阿新 • • 發佈:2018-11-20
public class FileUtils { private static final String ENCODING = "UTF-8";//編碼方式 /** * 獲取檔案的行 * * @param fileName * 檔名稱 * @return List<String> */ public static String getContentByLine(String fileName) { StringBuffer lines= new StringBuffer(); InputStreamReader read = null; BufferedReader bufferedReader = null; try { String configPath = FileUtils.class.getClassLoader().getResource(fileName).getPath(); configPath = configPath.replaceAll("%20", " ");// 處理檔案路徑中空格問題File file = new File(configPath); if (file.isFile() && file.exists()) { // 判斷檔案是否存在 read = new InputStreamReader(new FileInputStream(file), ENCODING); bufferedReader = new BufferedReader(read); String lineTxt= null; while ((lineTxt = bufferedReader.readLine()) != null) { if (lineTxt == null || lineTxt.length() == 0) { continue; } lines.append(lineTxt); } } } catch (Exception e) { e.printStackTrace(); } finally { try { if (read != null) { read.close(); } } catch (IOException e) { e.printStackTrace(); } finally { if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } } } return lines.toString(); } }