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


            这些天来获得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数组的形式在它返回。


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

  • 相关阅读:
    node实现将打包后的文件转压缩包
    Git/SVN忽略node_modules文件
    node实现发送邮件
    node搜索文件夹下的指定内容
    node批量修改文件文本内容
    微信小程序上线发布需要做的事情
    两件事 Jquery.form 锁
    .NET MVC 提交表单出现检测到有潜在危险的Request.Form值
    第一次使用TinyMCE
    第一次使用Entity Framework 的CodeFirst
  • 原文地址:https://www.cnblogs.com/gcczhongduan/p/4831276.html
Copyright © 2020-2023  润新知