Android读取文件时,由byte转成String字符串时出现乱码

先看看出乱码的代码

 public static void getInfo(Context context) {
        try {

            FileInputStream fileInputStream = context.openFileInput("hpPortal.txt");
            byte[] bytes = new byte[1024];
            int read = fileInputStream.read(bytes);
            String result = new String(bytes,"GB2312");
            Log.d("zhsy","read=="+read+"byte="+"text=="+result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

乱码截图:

Android读取文件时,由byte转成String字符串时出现乱码_第1张图片

起初以为是String后面的编码问题

String result = new String(bytes,"GB2312");

后来发现并没有起到效果,后来发现是byte【1024】的设置造成的,

所以改为代码:

byte[] bytes = new byte[fileInputStream.available()];

这样就ok了。

修改后的代码:

 public static void getInfo(Context context) {
        try {

            FileInputStream fileInputStream = context.openFileInput("hpPortal.txt");
            byte[] bytes = new byte[fileInputStream.available()];
            int read = fileInputStream.read(bytes);
            String result = new String(bytes,"GB2312");
            Log.d("zhsy","read=="+read+"byte="+"text=="+result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 

你可能感兴趣的:(android,编程中问题解决方案)