简体   繁体   English

android-无法保存文本文件

[英]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? 但是,每次我尝试运行代码时,应用都会崩溃,并显示错误消息“不幸的是,APP_NAME已停止。”有人可以告诉我我的代码有什么问题吗?

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. 从Android 6.0(API级别23)开始,用户在应用程序运行时(而不是在安装应用程序时)授予应用程序权限。 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 用户可以随时转到应用的“设置”屏幕来撤消权限

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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