zoukankan      html  css  js  c++  java
  • 不一致的文件编码读取和写入文件乱码解决方案

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


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

  • 相关阅读:
    Spark 基本概念及入门
    Cron 表达式详解
    VmWare 网络模式
    微信、支付宝各种支付退款
    Spring Security OAuth2 SSO 单点登录
    Git 入门详解
    基于Spring Boot 2.x 的 Spring Cloud Admin 实践
    Git 提交规范
    Linux 安装 Mysql8.0
    Docker入门
  • 原文地址:https://www.cnblogs.com/gcczhongduan/p/4831276.html
Copyright © 2011-2022 走看看