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


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM