码迷,mamicode.com
首页 > 其他好文 > 详细

不一致的文件编码读取和写入文件乱码解决方案

时间:2015-09-23 10:17:20      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:

        这些天来获得android数据加密中的应用。为了避免加密、解密算法被破解,我将成为核心的加密和解密算法使用JNI封装在一起,只有接口暴露java一层。

工作流程是这种:

1、通过自己写的加密解密工具将数据加密;

2、将加密的数据放在android的asserts目录下;

3、在首次使用数据时将asserts目录下的数据复制到一个隐藏目录下;

4、解密隐藏目录下的文件。


      在用加密工具将数据加密好了,在程序解密这个数据文件的过程中,发现解密出来的文件是原来文件大小的2倍,而且全是乱码,跟踪发现,主要问题出如今第3步,读写文件的编码方式不一致导致了文件乱码,之前我是用例如以下的方法来读取asserts目录下的内容的:

public static String readFileFromAssets(Context context, String fileName) throws IOException {
		if (null == context || TextUtils.isEmpty( fileName )){
			return null;
		}
		
		AssetManager assetManager = context.getAssets();
		InputStream input = assetManager.open(fileName);
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int length = 0;
		while ((length = input.read(buffer)) != -1) {
			output.write(buffer, 0, length);
		}
		output.close();
		input.close();
		
		return output.toString();
	}

       问题就出在我将读取出来的内容转换成了字符串,ByteArrayOutputStream的toString方法将文件内容转换成utf-8的编码了,但用C语言读写文件默认都是asii编码方式,读写文件的编码方式不一致导致了乱码问题,问题找到了,解决方法也就出来了,例如以下:

public static byte[] readFileFromAssets(Context context, String fileName) throws IOException {
		if (null == context || TextUtils.isEmpty( fileName )){
			return null;
		}
		
		AssetManager assetManager = context.getAssets();
		InputStream input = assetManager.open(fileName);
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int length = 0;
		while ((length = input.read(buffer)) != -1) {
			output.write(buffer, 0, length);
		}
		output.close();
		input.close();
		
		return output.toByteArray( );
		//return output.toString();
	}

        将读取asserts文件的内容以byte数组的形式在它返回。


版权声明:本文博主原创文章,博客,未经同意不得转载。

不一致的文件编码读取和写入文件乱码解决方案

标签:

原文地址:http://www.cnblogs.com/gcczhongduan/p/4831276.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!