AndroidStudio无法在模拟器上保存文件

时间:2018-11-24 18:36:07

标签: java android file filewriter

我想在模拟器的目录中保存/创建一个文件,但是我做不到,而且我不明白我的代码有什么问题。因此,每次我尝试运行代码时,都会说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();
        }
    }
}

}

1 个答案:

答案 0 :(得分:0)

我不知道它是否在您的清单中,但您正在与之合作

READ_EXTERNAL_STORAGE

在获得许可的情况下尝试

WRITE_EXTERNAL_STORAGE

希望这对您有帮助