Android写入txt文件防止中文乱码

//将输入框中的外部设备写入data.txt文件中
    public void write(String content) throws IOException {
        //创建一个带缓冲区的输出流
        String state= Environment.getExternalStorageState();
        if(state.equals(Environment.MEDIA_MOUNTED)){
            File SDPath=Environment.getExternalStorageDirectory();//SD根目录
            File file=new File(SDPath,"data.txt");
            FileOutputStream fos=new FileOutputStream(file);
            OutputStreamWriter writer=new OutputStreamWriter(fos,"utf-8");
            writer.write(content);
            writer.close();
            fos.close();
        }else {
            new AlertDialog.Builder(Main2Activity.this).setTitle("提示").setMessage("SD卡不可用")
                    .setPositiveButton("确定",null).create().show();
        }
    }

如果只是用FileOutStream写文件则不能控制编码方式,当再次读取时很容易出现乱码的情况。但是利用OutputStreamWriter提供的构造方法能够很好的控制编码。

读取文件是也是一样使用InputStreamWriter。

 
 
  //从data.txt读取内容
    public void read() throws IOException {
        //创建一个带缓冲区的输出流
        String state= Environment.getExternalStorageState();
        if(state.equals(Environment.MEDIA_MOUNTED)) {
            File SDPath = Environment.getExternalStorageDirectory();//SD根目录
            File file = new File(SDPath, "data.txt");
            //创建一个带缓冲区的输入流
            FileInputStream bis = new FileInputStream(file);
            InputStreamReader reader=new InputStreamReader(bis,"utf-8");
            int len;
            char[] buffer = new char[bis.available()];
            while ((len = reader.read()) != -1) {
                reader.read(buffer);
            }
            tv_read.setText(new String(buffer));
            reader.close();
            bis.close();
        }
    }



猜你喜欢

转载自blog.csdn.net/qq_38217237/article/details/79042019