简体   繁体   中英

android - can't save text file

The question is pretty common and I have googled it but it still wont work. I'm simply trying to save a text file using the below code:

                String state = Environment.getExternalStorageState();
                if (!Environment.MEDIA_MOUNTED.equals(state)) {
                    Toast.makeText(getApplicationContext(), "Access denied", Toast.LENGTH_LONG).show();
                }
                String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/data";
                File dir = new File(path);
                dir.mkdirs();
                File file = new File(path + "/savedFile.txt");
                String saveText = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
                FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream(file);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                try {
                    try {
                        fos.write(saveText.getBytes());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } finally {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_LONG).show();
                break;

and in my manifest I have declared:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

However everytime I try and run the code the app crashes with the error 'Unfortunately, APP_NAME has stopped." Can anyone tell me what is wrong with my code?

if ((checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)   == PackageManager.PERMISSION_GRANTED)&& Build.VERSION.SDK_INT >= 23 ) {
                Log.v(TAG,"Permission is granted");
                return true;}
              else{
              ActivityCompat.requestPermissions(this, new String[]Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
                  }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
            Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
             String state = Environment.getExternalStorageState();
            if (!Environment.MEDIA_MOUNTED.equals(state)) {
                Toast.makeText(getApplicationContext(), "Access denied", Toast.LENGTH_LONG).show();
            }
            String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/data";
            File dir = new File(path);
            dir.mkdirs();
             File file = new File(path + "/savedFile.txt");
            String saveText = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());

                 try {
                       fos = new FileOutputStream(file);
                       OutputStreamWriter ow =  new OutputStreamWriter(fos);
                       ow.write(saveText.getBytes());
                       ow.append(saveText.getText());
                       ow.close();
                       fos.close();
                       Toast.makeText(getBaseContext(),
                       "Done writing SD 'mysdfile.txt'",Toast.LENGTH_SHORT).show();
                     }} catch (Exception e) {
                            Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
                                           }

        }
    }

You need to use something like this code.Because you need to specify runtime permissions.Marshmallow needs you to check the permissions first to use respective resources. Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app. This approach streamlines the app install process, since the user does not need to grant permissions when they install or update the app. It also gives the user more control over the app's functionality; for example, a user could choose to give a camera app access to the camera but not to the device location. The user can revoke the permissions at any time, by going to the app's Settings screen

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM