环境getExternalStorageDirectory无法正常工作

时间:2019-01-01 18:44:03

标签: android storage environment

我想在Android Studio中创建一个文件夹和一个文本文件,但是不幸的是,在模拟器中既没有创建文件也没有创建文件夹。 我使用了两个示例代码,但没有用。  -logcat中没有任何错误

import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

package com.applike.filing;

import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        File localFile = new File(Environment.getExternalStorageDirectory(),"note");
        if (!localFile.exists()) {
            localFile.mkdir();
        }
        try{
            File gpxfile = new File(localFile, "text.txt");
            FileWriter writer = new FileWriter(gpxfile,true);
            writer.append("your file text");
            writer.flush();
            writer.close();
            Toast.makeText(this,"File NOT Created",Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

我还使用了以下代码,但没有回答

try {
    File dir = new File(Environment.getExternalStorageDirectory(), "note2");
    if (!dir.exists()) {
        dir.mkdir();
    }
    File txt = new File(dir, "test.txt");
    FileWriter fw = new FileWriter(txt);
    fw.append("Hello World");
    fw.close();
    Toast.makeText(this,"File Created",Toast.LENGTH_LONG).show();
}catch (IOException e){
    Toast.makeText(this,"File  Created",Toast.LENGTH_LONG).show();
}

enter image description here

Logcat

另外,我使用两个权限

WRITE_EXTERNAL_STORAGE-READ_EXTERNAL_STORAGE

2 个答案:

答案 0 :(得分:0)

    package com.applike.filetest2;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    EditText et_name, et_content;
    Button b_save;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1000);
        }

        et_name = (EditText)findViewById(R.id.filename);
        et_content = (EditText)findViewById(R.id.content);
        b_save = (Button)findViewById(R.id.benAdd);

        b_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String filename = et_name.getText().toString();
                String content = et_content.getText().toString();

                if(!filename.equals("") && !content.equals("")) {
                    saveTextAsFile(filename, content);
                }
            }
        });


    }
    private void saveTextAsFile(String filename, String content) {


        try{
         FileOutputStream fos = null;

         File dir = new File(Environment.getExternalStorageDirectory(),"folderTest");
         if(! dir.exists()){
             dir.mkdir();
         }
        String filenam = filename + ".txt";

     //    File n = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),filenam);
        File file = new File(dir, filenam);
        fos = new FileOutputStream(file);
        fos.write(content.getBytes());
        fos.close();
        Toast.makeText(this, "Saved!", Toast.LENGTH_SHORT).show();
    } catch (FileNotFoundException e) {
            e.printStackTrace();
            Toast.makeText(this, "file not found!", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "Error Saving!", Toast.LENGTH_SHORT).show();
        }
    }



    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case 10000:
                if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    Toast.makeText(this, "Premiss granrted", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(this, "Premiss not granrted", Toast.LENGTH_SHORT).show();
                    finish();
                }
        }
    }
}

答案 1 :(得分:0)

在Android Q中,似乎已弃用Environment.getExternalStorageDirectory()

尝试改用context.getExternalFilesDir(null)

https://developer.android.com/reference/android/os/Environment#getExternalStorageDirectory()

   /**
     * @deprecated To improve user privacy, direct access to shared/external
     *             storage devices is deprecated. When an app targets
     *             {@link android.os.Build.VERSION_CODES#Q}, the path returned
     *             from this method is no longer directly accessible to apps.
     *             Apps can continue to access content stored on shared/external
     *             storage by migrating to alternatives such as
     *             {@link Context#getExternalFilesDir(String)},
     *             {@link MediaStore}, or {@link Intent#ACTION_OPEN_DOCUMENT}.
     */
``