Question

I am trying to write a fake csv file , but I always get an IOException : file not found my code seems correct, but I may have missed something somewhere ... exception is raised on the filewriter = new FileWriter line

java.io.File file;
file = new File(context.getExternalFilesDir(null), "/swimmer/trainings/");
String mTrainingsPath = file.getPath();

String csvFilePath = mTrainingsPath + java.io.File.separator + training.filename;    
file = new File( csvFilePath);

 try {
 FileWriter fileWriter = new FileWriter( file );
 PrintWriter csvOut = new PrintWriter( fileWriter );

String data = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.\\n" 
+ " Cras facilisis elit eu nisl laoreet mollis.\\n" 
+ " In feugiat nec elit at tincidunt.";

csvOut.println( data );
csvOut.close();

} catch( IOException e ) {
Log.e(TAG, "IOException in creating csv file");
Log.e(TAG, "STACKTRACE");
Log.e(TAG, Log.getStackTraceString(e));
 }

here is the log file :

java.io.FileNotFoundException: /storage/emulated/0/Android/data/com.swimtechtest.swimmer/files/swimmer/trainings/myFirstTraining.csv: open failed: ENOENT (No such file or directory)
at libcore.io.IoBridge.open(IoBridge.java:409)
at java.io.FileOutputStream.<init>(FileOutputStream.java:88)
at java.io.FileOutputStream.<init>(FileOutputStream.java:73)
at java.io.FileWriter.<init>(FileWriter.java:42)
at ...swimmer.database.DatabaseHandler.putFakeTraining(DatabaseHandler.java:86

directory /storage/emulated/0/Android/data/com.swimtechtest.swimmer/files/swimmer/trainings/ exists (created previously)

Was it helpful?

Solution

You need to create your directories. Given your current local variable named file, call file.mkdirs() to create them. This will not throw an error if the directories already exist, so usually you just call mkdirs() before attempting to use the directory. Or, use exists() to see if it is there, then call mkdirs() if needed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top