直接用字節流讀取,可保留原格式,在拼裝字符串的時候能夠把編碼轉爲utf-8 防止亂碼,可是根據緩存byte數組的大小不一樣,會出現部分字符亂碼狀況數組
public static String readToText(String filePath) {//按字節流讀取可保留原格式,可是有部分亂碼狀況,根據每次讀取的byte數組大小而變化 StringBuffer txtContent = new StringBuffer(); byte[] b = new byte[2048]; InputStream in = null; try { in = new FileInputStream(filePath); int n; while ((n = in.read(b)) != -1) { txtContent.append(new String(b, 0, n, "utf-8")); } in.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } return txtContent.toString(); }
使用字符流的readline讀取出來不能保留文檔原格式,裏面的空格換行都失效了。可是沒有亂碼。最終解決辦法,是採用此方法,而後手動拼接換行符。代碼以下:緩存
public static String readtxt(String path) {//按行讀取,不能保留換行等格式,因此須要手動添加每行換行符。 // String result = ""; StringBuffer txtContent = new StringBuffer(); File file = new File(path); try { int len = 0; FileInputStream in = new FileInputStream(file); InputStreamReader reader = new InputStreamReader(in, "utf-8"); BufferedReader br = new BufferedReader(reader); String s = null; while ((s = br.readLine()) != null) { if (len != 0) {// 處理換行符的問題,第一行不換行 txtContent.append(new String(("\r\n" + s).getBytes(), "utf-8")); } else { txtContent.append(new String(s.getBytes(), "utf-8")); } len++; } reader.close(); in.close(); } catch (UnsupportedEncodingException | FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } /*try { BufferedReader br = new BufferedReader(new FileReader(new File(path))); String s = null; while((s=br.readLine())!=null){ result = result + "\n" + s; } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ return txtContent.toString(); }