網頁

2023年3月16日 星期四

Android Studio - Android 12 外部存儲空間讀寫檔案程式(一百一十)

Android Studio - Android 12 外部存儲空間讀寫檔案程式(一百一十):

筆者將 Android 12 外部存儲空間(External Storage)的路徑放入程式內作測試,外部存儲空間路徑也是蠻多,所以將資料匯集紀錄,因為很多時候需要讀寫本地檔的操作,將來作參考作用。這個程式是使用了 SAF(Storage Access Framework)框架,暫時解決了 Android 12 外部存儲空間讀寫檔案程式問題。


Android 12 外部存儲空間讀寫程式
操作系統:Windows 7 64-bit 版本
開發環境:Android Studio 4.0.1 版本
最低 SDK 版本:minSdkVersion 24
測試手機:Samsung Galaxy M33 5G
測試手機系統版本:Android 12(Snow Cone / 2021)
原程式:C:\Development\Development_Android\DIY-Android-190-15d Android12ReadWriteFile bugworkshop 20230304 - ReadWriteFileExt
程式:C:\Development\Development_Android\Android_Project\DIY-Android-190-15d Android12ReadWriteFile bugworkshop 20230304 - ReadWriteFileExt

MainActivity.java:

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_readwrite_ext);

 

        mbtn_save = (Button)findViewById(R.id.btn_save);

        mbtn_load = (Button)findViewById(R.id.btn_load);

        mtxt_filepath = (TextView) findViewById(R.id.text_path);

        mtxt_filecontent= (TextView) findViewById(R.id.text_content);

        mtxt_filecontent.setMovementMethod(new ScrollingMovementMethod());

        mlist_file = findViewById(R.id.list_file);

        medit_input = (EditText) findViewById(R.id.edittext_input);

 

        myfolder= getFilesDir();

        myFilename = new File(getFilesDir(), filename);

 

        mbtn_save.setOnClickListener(new View.OnClickListener()

        {

            @Override

            public void onClick(View v) {

                filePicker(false);

            }

        });

 

        mbtn_load.setOnClickListener(new View.OnClickListener()

        {

            @Override

            public void onClick(View v) {

                read();

            }

        });

}

 

   ActivityResultLauncher<Intent> mLaunchFilePicker = registerForActivityResult(

            new ActivityResultContracts.StartActivityForResult(), result -> {

                Intent data = result.getData();

                if (result.getResultCode() == Activity.RESULT_OK && data != null) {

                    handleFileResult(data,true);

                }

            });

 

    ActivityResultLauncher<Intent> mLaunchFileSaver = registerForActivityResult(

            new ActivityResultContracts.StartActivityForResult(), result -> {

                Intent data = result.getData();

                if (result.getResultCode() == Activity.RESULT_OK && data != null) {

                    handleFileResult(data,false);

                }

            });

 

    void filePicker(boolean readOrWrite) {

        if (readOrWrite) {

            intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);

            intent.setType("*/*");

            intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);

            intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);

            mLaunchFilePicker.launch(intent);

        } else {

            intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);

            intent.setType("text/*");

            intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);

            intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);

            mLaunchFileSaver.launch(intent);

 

        }

    }

 

    private void handleFileResult(Intent data, boolean readOrWrite) {

        mFileUri = data.getData();

 

        if (mFileUri != null) {

            try {

                getContentResolver().takePersistableUriPermission(mFileUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);

            } catch (SecurityException e) {

                e.printStackTrace();

            }

            if (readOrWrite) {

                read();

            } else {

                write();

            }

        }

    }


MainActivity.java - Read External Storage File:

    void read() {

 

        try {

            InputStreamReader inputStreamReader = new InputStreamReader(getContentResolver().openInputStream(mFileUri));

            BufferedReader reader = new BufferedReader(inputStreamReader);

            StringBuilder builder = new StringBuilder();

            try {

                String fileContentLine;

                while ((fileContentLine = reader.readLine()) != null) {

                    fileContentLine += "\n";

                    builder.append(fileContentLine);

                }

                String fileContent = builder.toString();

                mtxt_filecontent.setText(fileContent);

                medit_input.setText(fileContent);

            } finally {

                mtxt_filepath.setText(mFileUri.toString());

                reader.close();

                inputStreamReader.close();

            }

        } catch (IOException e) {

            e.printStackTrace();

        }

    }


MainActivity.java - Write External Storage File:

    void write() {

        mtxt_filepath.setText("Save File=" + mFileUri.toString());

 

        try {

            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(getContentResolver().openOutputStream(mFileUri));

            BufferedWriter writer = new BufferedWriter(outputStreamWriter);

            String textContent = medit_input.getText().toString();

 

            try {

                writer.write(textContent);

            } finally {

                writer.close();

                outputStreamWriter.close();

            }

        } catch (IOException e) {

            e.printStackTrace();

        }

    }


Android 12 外部存儲空間寫入程式
Android 12 外部存儲空間寫入程式
Android 12 外部存儲空間讀取程式




沒有留言:

張貼留言