java读取文件里面部分汉字内容乱码的解决方案

网友投稿 259 2023-01-06

java读取文件里面部分汉字内容乱码的解决方案

java读取文件里面部分汉字内容乱码

读取一个txt文件,到代码中打印出来,发票有部分汉字的内容是乱码的。

我开始的方式是这样的, 如下,这是完全错误的,汉字是两个字节的,如果每次读固定个字节,可能会把汉字截断。

就会出现部分乱码的情况。

package susq.path;​

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

/**

* @author susq

* @since 2018-05-18-19:28

*/

public class WrongMethodReadTxt {

public static void main(String[] args) throws IOException {

ClassLoader classLoader = WrongMethodReadTxt.class.getClassLoader();

String filePath = classLoader.getResource("").getPath() + "/expect1.txt";

System.out.println(filePath);

File file = new File(filePath);

try (FileInputStream in = new FileInputStream(file)) {

byte[] bytes = new byte[1024];

StringBuffer sb = new StringBuffer();

int len;

while ((len = in.read(bytes)) != -1) {

sb.append(new String(bytes, 0, len));

}

System.out.println(sb.toString());

}

}

}

如果存在汉字,就要按字符的方式读取:

package susq.path;​

import java.io.BufferedReader;

import java.io.File;

import java.io.FileReader;

import java.io.IOException;

/**

* @author susq

* @since 2018-05-18-17:39

*/

public class SysPath {

public static void main(String[] args) throws IOException {

ClassLoader classLoader = SysPath.class.getClassLoader();

String filePath = classLoader.getResource("").getPath() + "/expect1.txt";

203;

System.out.println(filePath);

File file = new File(filePath);

try (BufferedReader br = new BufferedReader(new FileReader(file))) {

StringBuffer sb = new StringBuffer();

while (br.ready()) {

pXDLDhM sb.append(br.readLine());

}

System.out.println(sb);

}

}

}

java的IO流读取数据时,解决中文乱码,还有个别中文乱码问题

情况:用IO流读取数据时,若是不设置编码格式,出来的数据未必是我们所要的

解决:读取数据时,设置编码

代码:(字符串设置对应的编码即可,但这种方式,会导致个别中文乱码,貌似是byte[]导致的)

//这里我通过socket方式,获取流,并读取数据

//代理需要外置配置(代理配置需要判断,若有配置,则添加,若无配置,则不添加)

Socket socket = new Socket("192.168.99.100", 80);

String url = "GET " + href + " HTTP/1.1\r\n\r\n";

socket.getOutputStream().write(new String(url).getBytes());

InputStream is = socket.getInputStream();

byte[] bs = new byte[1024];

int i;

StringBuilder str = new StringBuilder();

while ((i = is.read(bs)) > 0) {

//一定要加编码,不然,在输出到文件时,部分数据会乱

str.append(new String(bs, 0, i,"UTF-8"));

//由于socket读取不会断开,所以只能自断开连接读取

if(new String(bs, 0, i,"UTF-8").contains("

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:SpringAOP 如何通过JoinPoint获取参数名和值
下一篇:查找网站api接口(如何查看网站api)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~