I am trying to write to a text file in Android. My code is as follows (running in a Service):
File log; String state = Environment.getExternalStorageState(); File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { log = new File(path, "log.csv"); System.out.println("Opening file"); } else { System.err.println("Could not write to external storage medium. No log will be created"); return; } String line = "stuff"; if (!log.exists()) { try { log.createNewFile(); System.out.println("Creating new log file."); } catch (IOException e) { System.err.println("Could not create new log file"); e.printStackTrace(); return; } } try { path.mkdirs(); BufferedWriter bw = new BufferedWriter(new FileWriter(log, true)); bw.append(line); System.out.println("Appending to log file."); bw.newLine(); bw.flush(); bw.close(); } catch (IOException e) { System.err.println("Failed to write to log file"); e.printStackTrace(); return; } And I have put the following line in AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> When I run this, the following is printed in LogCat:
Opening file Appending to log file. But I can't find any files with the given name on the phone's memory, despite looking in the desired directory and running a search to see if it's somewhere else instead.
I'm not sure what could be going wrong. Any ideas? Thanks!