標籤:put tco ret generate buffer byte tostring tac pat
直接用位元組流讀取,可保留原格式,在拼裝字串的時候可以把編碼轉為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(); }
android讀去txt 為string