600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > java读取txt文件乱码解决方法

java读取txt文件乱码解决方法

时间:2019-02-27 03:38:10

相关推荐

java读取txt文件乱码解决方法

Java|Java基础

java

Java-Java基础

代理查询系统源码,ubuntu如何设置投影,linux上写爬虫,php fwite,晓客seolzw

java读取txt文件,如果编码格式不匹配,就会出现乱码现象。所以读取txt文件的时候需要设置读取编码。txt文档编码格式都是写在文件头的,在程序中需要先解析文件的编码格式,获得编码格式后,在按此格式读取文件就不会产生乱码了。(推荐:java视频教学)

金蝶云会计php源码,vscode c c 扩展,ubuntu安装 中文,tomcat 支持中文,sqlite图片库,网页设计站点,远程连接sql2000数据库,香港多ip站群服务器,bootstrap chart插件,前端框架需要设计ui吗,爬虫运行环境,php as,枫林seo工具,springboot邮件,标签,网站建设前台后台教程,网页下方有网址,安卓软件文档模板,网页后台测试,漂亮404页面,西部数字房屋中介信息管理系统 企业版,推荐几个好的seo网站程序模板lzw

java编码与txt编码对应:

网校 aspx源码,vscode 更新日志,ubuntu 耗电问题,sts配置tomcat启动,googleplay爬虫,php split 中文,马尾seo网络营销,虚拟网站平台源码,织梦判断栏目调用模板lzw

示例:

package com.lfl.attachment; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; public class TextMain { public static void main(String[] args) throws Exception {String filePath = "D:/article.txt"; //String filePath = "D:/article333.txt"; //String filePath = "D:/article111.txt"; String content = readTxt(filePath);System.out.println(content);}/*** 解析普通文本文件 流式文件 如txt* @param path* @return*/@SuppressWarnings("unused")public static String readTxt(String path){StringBuilder content = new StringBuilder("");try { String code = resolveCode(path); File file = new File(path); InputStream is = new FileInputStream(file); InputStreamReader isr = new InputStreamReader(is, code); BufferedReader br = new BufferedReader(isr); //char[] buf = new char[1024]; //int i = br.read(buf); //String s= new String(buf); //System.out.println(s); String str = ""; while (null != (str = br.readLine())) { content.append(str); } br.close();} catch (Exception e) { e.printStackTrace(); System.err.println("读取文件:" + path + "失败!");}return content.toString();} public static String resolveCode(String path) throws Exception { //String filePath = "D:/article.txt"; //[-76, -85, -71] ANSI //String filePath = "D:/article111.txt"; //[-2, -1, 79] unicode big endian //String filePath = "D:/article222.txt"; //[-1, -2, 32] unicode //String filePath = "D:/article333.txt"; //[-17, -69, -65] UTF-8InputStream inputStream = new FileInputStream(path); byte[] head = new byte[3]; inputStream.read(head); String code = "gb2312"; //或GBKif (head[0] == -1 && head[1] == -2 )code = "UTF-16"; else if (head[0] == -2 && head[1] == -1 )code = "Unicode"; else if(head[0]==-17 && head[1]==-69 && head[2] ==-65)code = "UTF-8"; inputStream.close();System.out.println(code); return code;} }

注意:在resolveTxt方法中不能通过readTxt方法传InputStream流 ,这样会使两个方法持有同一个流引用,而在resolveTxt方法中已读过流中的三个字节,流中的pos此时已经是3了,而不是流的起始位置,再在readTxt中读取时就会出现IOException:Read Error。

更多java知识请关注java基础教学栏目。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。