idea中使用Inputstream流导致中文乱码解决方法
idea中使用Inputstream流导致中文乱码解决方法
很多朋友遇到一个措手不及的问题当idea中使用Inputstream流导致中文乱码及Java FileInputStream读中文乱码问题,针对这两个问题很多朋友不知道该如何解决,下面小编把解决方案分享给大家供大家参考
1.问题描述
idea中使用Inputstream流导致中文乱码解决方法,当然也不一定就是输入流,可能输出流或者其他用到了流相关的字符的都可能出现乱码,这里有一个可能的解决办法。
2. 解决办法
① idea中找到下面的路径
File--Settings--Editor--File Encodings
② Transparent native-to-ascii conversion把这个前面勾上,重新创建文件,执行就OK
很多朋友遇到Java FileInputStream读中文乱码问题,下面小编在给大家普及下这方便的知识及解决方法。
1、前提
以读取编码是GBK的文件为案例,文件内容只有中文和中文符号
2、原因
FileInputStream读中文乱码是因为一个中文对应两个字节存储(负数),也就是说,读取对应中文的字节数应该是偶数; 而英文对应一个字节存储。FileInputStream每次读取一个数组长度的字节时,读取的中文字节数可能是奇数,也就是只读到中文的一半字节,出现乱码。
3、解决方法
一次读取所有字节,此方法不靠谱,因为不确定总字节数。
在输出时进行判断,遍历数组判断负数的个数,如果是奇数,说明读取到中文的一半字节,对数组进行扩容再输出;否则正常输出
4、代码案例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 | package 第二题; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Arrays; public class MainTest { public static void main(String[] args) throws UnsupportedEncodingException { // 创建File对象 File file = new File( "D:\\filetest\\file4.txt" ); FileInputStream fileInputStream = null ; try { // 新建一个FileInputStream对象 fileInputStream = new FileInputStream(file); // 新建一个字节数组 byte [] buf = new byte [ 2 ]; // read(buf):此方法的返回值就是当前读取的字节个数,将数据读取到buf数组 // 将readLen变量也就是read方法的返回值,当此变量等于-1,则读到文件末尾 int readLen = - 1 ; //读取文件数据 while ((readLen = fileInputStream.read(buf)) != - 1 ) { int pos= 0 ; //记录负数的个数 for ( byte v:buf) { if (v< 0 ) { pos++; } } //负数个数为偶数,读取完整,没有读取到半个中文 if (pos% 2 == 0 ) { // 将字节数组转换成字符串 String content = new String(buf, 0 , readLen); System.out.print(content); } else { //负数个数为奇数,读取不完整,会乱码 //再读取下一位字节 int nextByteValue=fileInputStream.read(); int nextLen=readLen+ 1 ; //字节数组扩容一位 buf= Arrays.copyOf(buf,nextLen); buf[readLen]= ( byte ) nextByteValue; String content= new String(buf, 0 ,nextLen); System.out.print(content); //奇数,字节补全 //针对数组扩容一个字节单元 /* buf=Arrays.copyOf(buf, readLen+1); int nextByteValue=fileInputStream.read(); buf[readLen]= (byte) nextByteValue; String content = new String(buf, 0, readLen); System.out.print(content);*/ } } } catch (FileNotFoundException e) { // 输出堆栈信息 e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { // 文件输入流关闭(释放资源) fileInputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } |
以上就是idea中使用Inputstream流导致中文乱码解决方法的详细内容
原文链接:https://blog.csdn.net/qq_43987149/article/details/117404396