How to create a file and check if it is there. I attach the code. (If you have already reached this point, you do not need to reach it, if it is the first time, then an achievement should appear accordingly)

public void showToast(View view) { String fileDir = "file"; File f = new File(fileDir); if (f.exists()) { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); }else{ try { new File(fileDir).createNewFile(); } catch (IOException e) { e.printStackTrace(); } Toast toast = Toast.makeText(getApplicationContext(), "Получена первая награда!", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER, 0, 0); LinearLayout toastContainer = (LinearLayout) toast.getView(); ImageView RewardImage = new ImageView(getApplicationContext()); RewardImage.setImageResource(R.drawable.reward); toastContainer.addView(RewardImage, 0); toast.show(); Intent intent = new Intent(this, MainActivity.class); startActivity(intent); } 

Does not work. Tell me what to do. Thank you in advance.

  • one
    Check that the application has permission to write. And tell me, why for the last couple of days, so many people are asking how to create files) - Yuriy SPb
  • I did not add write permission. How to make it? - Styopkin Stepan
  • It is better to create a file in the application's private directory context.getFilesDir() . For this, no permissions are needed and this file will not be visible to other applications. - eugeneek
  • Students pass tests - Barmaley

1 answer 1

To save files, it is better to use the application directory - as it was mentioned by eugeneek , to get it you can use: context.getFilesDir() (If it underlines red and it is not clear why - learn what there is a context - in Russian with examples here: http: //developer.alexanderklimov .ru / android / theory / context.php ).

Your code will look something like this:

 String pathToFile = getFilesDir() + "\\"; String fileName = "file; File f = new File(pathToFile + fileName); if (f.exists()){ ... }else{ try { new File(pathToFile + fileName).createNewFile(); } catch (IOException e) { e.printStackTrace(); } .... } 
  • Thank. Finally, the code earned - Styopkin Stepan