【问题标题】:AndroidStudio unable to save a file on the EmulatorAndroid Studio 无法在模拟器上保存文件
【发布时间】:2019-04-26 22:11:41
【问题描述】:

我想在我的模拟器目录中保存/创建一个文件,但我不能这样做,我不明白我的代码有什么问题。所以每次我尝试运行代码时,它都会说android无法在这样的目录中创建文件。 有人可以向我解释一下我是如何做到的。这是我的应用程序的代码:

公共类 MainActivity 扩展 AppCompatActivity {

private int STORAGE_PERMISSION_CODE = 1;
private File csvFile;
SimpleDateFormat TIME;

private static final String CSV_DIRECTORY = "NameOfTheDirectory";

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

    if((ContextCompat.checkSelfPermission(MainActivity.this,
            Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED)){
        Toast.makeText(MainActivity.this, "You have already granted this permission",
                Toast.LENGTH_SHORT).show();
    }else {
        requestStoragePermission();
    }
}

public void makeFile(View view) {
    File csvDirectory = new File(
            Environment.getExternalStorageDirectory().getAbsolutePath() +
                    File.separator + CSV_DIRECTORY);
    if(!csvDirectory.exists()) {
        try{
            csvDirectory.mkdir();
            Log.d("StateMakeFile","Directory created");
        } catch(Exception e) {
            e.printStackTrace();
            Log.d("StateMakeFile","Directory not created");
        }
    }
    File categoryDirectory = new File(
            Environment.getExternalStorageDirectory().getAbsolutePath() +
                    File.separator + CSV_DIRECTORY + File.separator + "NameOfTheCategory");
    if(!categoryDirectory.exists()){
        try{
            categoryDirectory.mkdir();
            Log.d("StateMakeFile","CategoryDirectory created");
        }catch (Exception e){
            e.printStackTrace();
            Log.d("StateMakeFile","CategoryDirectory not created");
        }
    }
    TIME = new SimpleDateFormat("yyyyMMdd-hh:mm:ss:SSS", Locale.getDefault());
    String uniqueFileName = TIME.format(new Date());
    csvFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +
            File.separator + CSV_DIRECTORY + File.separator + "NameOfTheCategory" +
            File.separator + uniqueFileName + ".csv");
    if(!csvFile.exists()){
        try{
            csvFile.createNewFile();
            Log.d("StateMakeFile","File created");
        }catch (IOException e){
            e.printStackTrace();
            Log.d("StateMakeFile","File not created");
        }
        if(csvFile.exists()) {
            try{
                PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(csvFile, true)));
                out.write("Something" + "\n");
                out.flush();
                out.close();
                Log.d("StateMakeFile","File was writed with success");
            }catch (IOException e){
                e.printStackTrace();
                Log.d("StateMakeFile","File wasnt writed with success");
            }
        }
    }

}

private void requestStoragePermission() {
    if (ActivityCompat.shouldShowRequestPermissionRationale(this,
            Manifest.permission.READ_EXTERNAL_STORAGE)) {

        new AlertDialog.Builder(this)
                .setTitle("Permission needed")
                .setMessage("This permission is needed to save and load files into ssd")
                .setPositiveButton("ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ActivityCompat.requestPermissions(MainActivity.this,
                                new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
                    }
                })
                .setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .create().show();

    } else {
        ActivityCompat.requestPermissions(this,
                new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    if (requestCode == STORAGE_PERMISSION_CODE)  {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "Permission GRANTED", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "Permission DENIED", Toast.LENGTH_SHORT).show();
        }
    }
}

}

【问题讨论】:

    标签: java android file filewriter


    【解决方案1】:

    我不知道它是否在您的清单中,但您正在这里工作

    READ_EXTERNAL_STORAGE

    在许可的情况下尝试

    WRITE_EXTERNAL_STORAGE

    希望对你有帮助

    【讨论】:

    • 哦,真的,我完全没看到,谢谢我现在试试,我希望现在可以工作
    猜你喜欢
    • 1970-01-01
    • 2021-09-25
    • 1970-01-01
    • 2017-03-26
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    • 2016-01-08
    • 2021-12-11
    相关资源
    最近更新 更多