不知道为什么保存文件后之前打开一直都 OK, 就突然打开看到变成乱码了, 最后解决了
关键: outStream.write(finalContent.getBytes("gbk"));
write 的时候设置一下: 转换格式 (UFT-8 在 Android 不能用, 只能用 gbk)!!! 我之前试过 utf-8, 还是乱码, 没什么用, 就是 gbk!
从项目里面抽取了这个把 String 保存为 txt 到本地的方法:
- String sdCardDir =Environment.getExternalStorageDirectory().getAbsolutePath();
- File saveFile = new File(sdCardDir, "aaaa.txt");//new FileOutputStream(file, true);true: 不覆盖写入文件
- FileOutputStream outStream = null;
- try {
- outStream = new FileOutputStream(saveFile);
- outStream.write(finalContent.getBytes("gbk"));//UFT-8 在 Android 不能用, 只能用 gbk!!! 不设置的话可能会变成乱码!!!
- outStream.close();
- outStream.flush();
- isSave = true;
- Toast.makeText(PusherEndActivity.this, "文件已经保存啦! 赶快去查看吧!", Toast.LENGTH_SHORT).show();
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
顺便贴一下 按一个 button, 然后跳转到文件管理器, 打开 txt 的方法, 我这里有个 isSave 布尔类型判断了一下是不是之前已经保存了文件
- btn_open_txt.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- if (isSave){
- String path = Environment.getExternalStorageDirectory().getPath();
- File file = new File(path);
- Intent intent1 = new Intent(Intent.ACTION_GET_CONTENT);
- intent1.addCategory(Intent.CATEGORY_DEFAULT);
- intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- intent1.setDataAndType(Uri.fromFile(file), "text/plain");
- try {
- startActivity(intent1);
- finish();
- // startActivity(Intent.createChooser(intent,"选择浏览工具"));
- } catch (ActivityNotFoundException e) {
- e.printStackTrace();
- }
- }else {
- Toast.makeText(PusherEndActivity.this, "还没有保存文件哦!", Toast.LENGTH_SHORT).show();
- }
- }
- });
感谢: https://blog.csdn.net/wsqfwqfsdge3wg/article/details/54614089 成功解决我的问题
来源: http://www.bubuko.com/infodetail-3037563.html