-2

The delete() doesn't work, because it does't delete file, and method exists returns false. Where is my mistake? There are problem code. Also I pasted all code on pastebin Sorry for my English. All code is here

public class MainActivity extends AppCompatActivity {

private EditText etText, etFileName;

@Override
protected void onCreate(Bundle savedInstanceState) {}

private void openFile(String fileName) {}

private void saveFile(String fileName) {}

private void clear() {}

private void delete(String fileName) {
    try {
        Log.d("MYTAG", fileName);
        File file = new File(fileName);
        Log.d("MYTAG", new File(".").getAbsolutePath());
        Log.d("MYTAG", Boolean.toString(file.exists()));
        file.delete();
        Log.d("MYTAG", Boolean.toString(file.exists()));
    } catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(getApplicationContext(), "Такого файла не существует!", Toast.LENGTH_SHORT).show();
    }
}

public void onClick(View view) {
    switch (view.getId()) {
        case R.id.save:
            saveFile(etFileName.getText().toString() + ".txt");
            break;
        case R.id.open:
            openFile(etFileName.getText().toString() + ".txt");
            break;
        case R.id.del:
            delete(etFileName.getText().toString() + ".txt");
            break;
        case R.id.clear:
            clear();
            break;
    }
}

}

1 Answers1

0

Use file.getAbsoluteFile().delete(), instead of file.delete() also check the returned boolen to be sure the file has been deleted, so, your delete function will be something like this

private void delete(String fileName) {
   try {
        File file = new File(fileName);
        if(!file.exists()){
            Toast.makeText(getApplicationContext(), "File doesn't exists", Toast.LENGTH_SHORT).show();
        } else if(file.getAbsoluteFile().delete())
            Toast.makeText(getApplicationContext(), "File has been deleted", Toast.LENGTH_SHORT).show();
        else
            Toast.makeText(getApplicationContext(), "File couldn't be deleted", Toast.LENGTH_SHORT).show();
      } catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(getApplicationContext(), "Такого файла не существует!", Toast.LENGTH_SHORT).show();
    }
}

Also make sure your app has the write permission to external storage

check here for more info for permissions:Storage permission error in Marshmallow

Sujan Poudel
  • 794
  • 5
  • 16
  • `Toast.makeText(getApplicationContext(), "File doesn't exists", Toast.LENGTH_SHORT).show();` Which file? Why not tell which file? `Toast.makeText(getApplicationContext(), file.getAbsolutePath() + "\n\nFile doesn't exists", Toast.LENGTH_LONG).show();` – blackapps Dec 15 '19 at 17:13