1. 程式人生 > >解決Android Studio 將String類型保存為.txt文件,按下button跳轉到文件管理器(解決了保存txt文件到文件管理後,手機打開是亂碼的問題)

解決Android Studio 將String類型保存為.txt文件,按下button跳轉到文件管理器(解決了保存txt文件到文件管理後,手機打開是亂碼的問題)

判斷 text 文件管理器 length button director ioe support get

不知道為什麽保存文件後之前打開一直都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 成功解決我的問題

解決Android Studio 將String類型保存為.txt文件,按下button跳轉到文件管理器(解決了保存txt文件到文件管理後,手機打開是亂碼的問題)