android读去txt 为string
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了android读去txt 为string,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1971字,纯文字阅读大概需要3分钟。
内容图文
![android读去txt 为string](/upload/InfoBanner/zyjiaocheng/1067/9d352da1b0854bf8a8d817d749443d76.jpg)
直接用字节流读取,可保留原格式,在拼装字符串的时候可以把编码转为utf-8 防止乱码,但是根据缓存byte数组的大小不同,会出现部分字符乱码情况
public static String readToText(String filePath) {//按字节流读取可保留原格式,但是有部分乱码情况,根据每次读取的byte数组大小而变化 StringBuffer txtContent = new StringBuffer(); byte[] b = newbyte[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(); }
原文:http://www.cnblogs.com/epmouse/p/6950987.html
内容总结
以上是互联网集市为您收集整理的android读去txt 为string全部内容,希望文章能够帮你解决android读去txt 为string所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。