How to check whether a file exists or not? If it does, read it, otherwise create it and write it ...
Tried to create a file like this:
File myF = new File(Environment.getDataDirectory(),"file.txt"); try { myF.createNewFile(); text.setText(myF.getAbsolutePath()); } catch (IOException e1) { text.setText(e1.toString()); } As a result, writes java.io.IOException: Permission denied
And in any case, when using the createNewFile() method, it createNewFile() out ...
After a long walk on an Internet, I found a solution to my problem ...
Initially, the following line should be added to the application's manifest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission> Then everything happens like this:
File myF = new File(Environment.getExternalStorageDirectory() + "/data/", "file.txt"); if (!myF.exists()) { try { String str = "0"; myF.createNewFile(); try { FileOutputStream fOut = openFileOutput(myF.getAbsolutePath(), 0); OutputStreamWriter outStr = new OutputStreamWriter(fOut); outStr.write(str); outStr.flush(); outStr.close(); } catch (Throwable t) { Toast.makeText(getApplicationContext(), "Exception: " + t.toString(), Toast.LENGTH_LONG).show(); } } catch (IOException e1) { text.setText(e1.toString()); } } else { text.setText("Файл есть!"); } But now it comes out:
java.lang.IllegalArgumentException: File mnt // sdcard // data // file.txt contains a path separator
Polaziv found that " openFileOutput can not accept the path, but only the file name .."
But then how will the file be created?