有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我想在模拟器的目录中保存/创建一个文件,但我不能这样做,我不明白我的代码有什么问题。所以每次我试着运行代码时,它都会说安卓无法在这样的目录中创建文件。 有人能解释一下我是怎么做到的吗。以下是我的申请代码:

公共类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();
        }
    }
}

}


共 (0) 个答案