Android 9 读写SD卡文件

AndroidManifest.xml




    
    

    
        
            
                

                
            
        
    

Actvity 部分:



    
    
    
源码部分:
package com.example.sddemo;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = MainActivity.class.getSimpleName();
    private static final String FILE_NAME="Arctan.txt";
    private static final int writeCode = 0x123;
    private static final int readCode = 0x456;
    private Button btRead;
    private Button btWrite;
    private EditText editW;
    private EditText editR;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btRead = findViewById(R.id.btRead);
        btWrite = findViewById(R.id.btWrite);
        editR = findViewById(R.id.read);
        editW = findViewById(R.id.write);
        Log.d(TAG, "onCreate: "+Environment.getExternalStorageDirectory());
        btWrite.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                MainActivity.writeCode);
            }
        });
        btRead.setOnClickListener(view->requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        MainActivity.readCode));
        
//        Log.d(TAG, "onCreate: "+ Environment.getExternalStorageDirectory());
    }

    private String read(){
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            File sdDir = Environment.getExternalStorageDirectory();
            try{
                FileInputStream fis = new FileInputStream(sdDir.getCanonicalPath()+"/"+FILE_NAME);

                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fis));
                StringBuilder sb = new StringBuilder();
                String line = null;

                while((line=bufferedReader.readLine())!=null){
                    sb.append(line);
                }
                return sb.toString();

            }catch (IOException e){
                Log.d(TAG, "read:catch");
                e.printStackTrace();
            }
        }
        return null;
    }
    private void write(String content){
        File sdDir = Environment.getExternalStorageDirectory();
        try{
            Log.d(TAG, "write: path "+sdDir.getCanonicalPath());
            File targetFile = new File(sdDir.getCanonicalFile()+"/"+FILE_NAME);
            RandomAccessFile raf = new RandomAccessFile(targetFile,"rw");
            raf.seek(targetFile.length());
            raf.write(content.getBytes());
            raf.close();
        }catch (IOException e){

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        Log.d(TAG, "onRequestPermissionsResult: peris "+Integer.toHexString(requestCode)+" pac "+ PackageManager.PERMISSION_GRANTED);
        if(requestCode == MainActivity.writeCode){
            if(grantResults != null && grantResults[0]==PackageManager.PERMISSION_GRANTED ){
                Log.d(TAG, "onRequestPermissionsResult: writeCode");
                write(editW.getText().toString());
            }else{
                Toast.makeText(MainActivity.this,R.string.write_warning,Toast.LENGTH_LONG).show();
            }

        }else if(requestCode == MainActivity.readCode){
            if(grantResults != null && grantResults[0]==PackageManager.PERMISSION_GRANTED ){
                Log.d(TAG, "onRequestPermissionsResult: readCode");
                editR.setText(read());
            }else{
                Toast.makeText(MainActivity.this,R.string.read_warning,Toast.LENGTH_LONG).show();
            }
        }


    }
}

你可能感兴趣的:(Android)