java读取文件里面部分汉字内容乱码
读取一个txt文件,到代码中打印出来,发票有部分汉字的内容是乱码的。
我开始的方式是这样的, 如下,这是完全错误的,汉字是两个字节的,如果每次读固定个字节,可能会把汉字截断。
就会出现部分乱码的情况。
package susq.path;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
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;
public class SysPath {
public static void main(String[] args) throws IOException {
ClassLoader classLoader = SysPath.class.getClassLoader();
String filePath = classLoader.getResource("").getPath() + "/expect1.txt";
System.out.println(filePath);
File file = new File(filePath);
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
StringBuffer sb = new StringBuffer();
while (br.ready()) {
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("</html>")){
break;
}
}
解决个别中文乱码问题:
代码:
//代理需要外置配置(代理配置需要判断,若有配置,则添加,若无配置,则不添加)
Socket socket = new Socket("192.168.99.100", 80);
//Socket socket = new Socket();
String url = "GET " + href + " HTTP/1.1\r\n\r\n";
socket.getOutputStream().write(new String(url).getBytes());
InputStream is = socket.getInputStream();
//解决个别中文乱码
StringBuilder str = new StringBuilder("");
InputStreamReader isr = new InputStreamReader(is,"UTF-8");
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
str.append(line + "\n");
if(line.contains("</html>")){
break;
}
}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。