Android输出csv文件乱码

问题:Android输出csv文件乱码

解决方案:
output.write(new byte[]{(byte) 0xEF, (byte) 0xBB,(byte) 0xBF}); //代码中的这个是为了解决乱码用的

//往SD卡写入文件的方法
    public static String savaFileToSD(String fileName, ArrayList<String> list,Context context) throws Exception {
        //如果手机已插入sd卡,且app具有读写sd卡的权限
        Log.d(TAG,"come in saveFileToSD");
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//            fileName = context.getExternalFilesDir(null).getAbsolutePath() + "/" + fileName; //内部存储
            fileName = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/" + fileName;
            Log.d(TAG,"savaFileToSD fileName:"+fileName);
            //这里就不要用openFileOutput了,那个是往手机内存中写数据的
            File file = new File(fileName);
            if (!file.exists()){
                file.createNewFile();
            }
            FileOutputStream output = null;
            OutputStreamWriter oStreamWriter = null;
            try {
                output = new FileOutputStream(fileName);
                output.write(new byte[]{(byte) 0xEF, (byte) 0xBB,(byte) 0xBF});
                oStreamWriter = new OutputStreamWriter(output, "utf-8");

                for (String sms :list){
                    oStreamWriter.append(sms);
                    oStreamWriter.append("\r\n");
                }
                //将String字符串以字节流的形式写入到输出流中
            } catch (Exception e) {
                Log.e(TAG, "saveFileTOSD error: " + e.getMessage(), e);
            } finally {
                try {
                    oStreamWriter.close();
                    output.close();
                    //关闭输出流
                } catch (Exception e) {
                }
            }

            return fileName;
        } else Toast.makeText(context, "SD卡不存在或者不可读写", Toast.LENGTH_SHORT).show();
        return "";
    }

猜你喜欢

转载自blog.csdn.net/yanwenyuan0304/article/details/131045164