FileWriter追加文件写入遇到的坑,默认是ISO-8859-1 或者 US-ASCII编码

一个同事需要把一个对账文件进行筛选,推送给第三方,很有意思的问题是,该第三方明确要求每一行文件必须固定长度,按照gbk进行编码,而且每一天的对账文件不管多大,尽量筛选控制在一个txt文件中,然后进行压缩传送,本来是挺简单的一件事,结果遇到了编码问题,第三方说我们的长度有问题,那同事说没问题,我检查了,代码中都是gbk编码,没有用到utf-8编码的,我去看了一眼,搜索了一下,的确代码中没有utf-8编码,但这还不足以打消我的疑虑,我继续追踪代码:

InputStreamReader inputReader = null;
BufferedReader bufferReader = null;
OutputStream outputStream = null;
try {
	InputStream iStream = new FileInputStream(file);
	inputReader = new InputStreamReader(iStream, "GBK");
	bufferReader = new BufferedReader(inputReader);

	// 读取一行
	String line = null;
    while ((line = bufferReader.readLine()) != null) {
		String[] st = line.split(";");
…………………………………………

读取文件,的确采用gbk方式,输出也没毛病,然后我让他自己读取自己生成的文件,进行长度校验一下,就用上面的代码,只不过把line这个地方,进行gbk编码字节,进行长度计算输出一下,他照做了,结果发现,中文长度那一栏目是有问题的:

while ((line = bufferReader.readLine()) != null) {
	System.out.println("GBK长==" + line.getBytes("GBK").length);
	System.out.println("UTF-8长==" + line.getBytes("UTF-8").length);
}

继续追踪,找到他追加写入的代码,用的竟然是FileWriter,而且还是网上复制来的,这就怪不得会出问题了,Java中FileWriter 默认是用(ISO-8859-1 或者 US-ASCII)西方编码的,并且FileWriter类并没有setEncoding的方法,所以用该方法追加写入文件,编码是肯定有问题的:

// 追加写入
public static void appendMethod(File fileName, String content) {
	try {
		// 打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
		FileWriter writer = new FileWriter(fileName, true);
		writer.write(content + "\n");
		writer.close();
	} catch (IOException e) {
		System.err.println("追加写入失败!");
	}
}

建议他把FileWriter换成FileOutputStream,问题得以解决:

public static void appendMethod(File file, String content, boolean addOr) {
	FileOutputStream fileOutputStream = null;
	try {
		if (!file.exists()) {
			file.createNewFile();
		}
		fileOutputStream = new FileOutputStream(file, true);
		fileOutputStream.write(content.getBytes("gbk"));

	} catch (IOException e) {
		log.error("追加写入文件错误!" + e);
	} finally {
		if (fileOutputStream != null) {
			try {
				fileOutputStream.flush();
				fileOutputStream.close();
			} catch (IOException e) {
				log.error("关闭写入文件错误!" + e);
			}
		}
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值