【问题解决】读取文件内容乱码的解决方案

问题描述

使用FileReader & BufferedReader读取文件内容,输出String,获取的内容为乱码。代码为:

/**
 * 从文件读内容
 * @param filePath
 * @return
 */
public static String readFromFile(String filePath) {
	String result = null;
	FileReader fileReader = null;
	BufferedReader bufferedReader = null;
	try {
		fileReader = new FileReader(filePath);
		bufferedReader = new BufferedReader(fileReader);
		try {
			String read = null;
			while ((read = bufferedReader.readLine()) != null) {
				result = result + read + "\r\n";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		if (bufferedReader != null) {
			try {
				bufferedReader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (fileReader != null) {
			try {
				fileReader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	return result;
}
解决方案
方法一

  还是读取以上的文件内容,读取文件内容后,将String转为bytes数组,再从bytes数组转为String,并指定编码

bytes [] jsonBytes = jsonStr.getBytes();
String json = new String(jsonBytes, "UTF-8");
方法二

  先读取文件内容为bytes数组,使用ByteArrayOutputStream,代码如下:

public static byte[] fileToBytes(String filePath) {
	byte[] buffer = null;
	try {
		File file = new File(filePath);
		FileInputStream fis = new FileInputStream(file);
		ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
		byte[] b = new byte[1000];
		int n;
		while ((n = fis.read(b)) != -1) {
			bos.write(b, 0, n);
		}
		fis.close();
		bos.close();
		buffer = bos.toByteArray();
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
	return buffer;
}

  再将bytes数组转为String,并指定编码格式

byte[] jsonBytes = FileUtil.fileToBytes(jsonFile);
String json = new String(jsonBytes, "UTF-8");
方法三

  初始化BufferedReader时候,使用InputStreamReader并指定编码格式来替换FileReader

BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(fileName),"UTF-8"));
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值