Reputation: 81
I'm trying to create a txt file in internal storage. When I execute the action and call the function responsible for creating the file, no error occurs. However when I check if the file was actually created in the /data/data/ folder, I can not find the folder with the name of my package.
Where is the error?
Ps.: I already saw several links from here on the subject, but in all cases the same case.
public void criarArq(Context mcoContext,String sFileName, String sBody){
File file = new File(mcoContext.getFilesDir(),"mydir");
if(!file.exists()){
file.mkdir();
}
try{
File gpxfile = new File(file, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
}catch (Exception e){
}
}
And I call the function this way...
criarArq(getApplicationContext(), arqNome, "teste");
Thank you for all help!
--- Update ---
This is my code now:
try {
FileWriter writer = new FileWriter(gpxfile);
writer.append("teste");
writer.flush();
writer.close();
Toast.makeText(InfoEntregasActivity.this, "created",
Toast.LENGTH_LONG).show();
} catch (IOException e) {
//Don't eat the exception, do something with it, e.g.
Log.e("criarArq", e.toString()); //this will give you your error in the log cat
Toast.makeText(InfoEntregasActivity.this, e.toString(),
Toast.LENGTH_LONG).show();
throw new RuntimeException(e); //this will bomb your program out for when the error is unrecoverable
}
I try with and without the Toast (same result), but with Toast I always get "created" msg.
Upvotes: 1
Views: 897
Reputation: 54791
...no error occurs
You're eating any potential exception, so I wouldn't be so sure.
public void criarArq(Context mcoContext, String fileName, String body) {
File file = new File(mcoContext.getFilesDir(),"mydir");
file.mkdirs(); //no need to check exists with mkdirs
File gpxfile = new File(file, fileName);
try {
FileWriter writer = new FileWriter(gpxfile);
writer.append(body);
writer.flush();
writer.close();
} catch (IOException e) {
//Don't eat the exception, do something with it, e.g.
Log.e("criarArq", e.toString()); //this will give you your error in the log cat
throw new RuntimeException(e); //this will bomb your program out for when the error is unrecoverable
}
}
Additional tips, mkdirs
makes multiple levels and does the exists
check for you.
Do not use prefixes relating the to type, e.g. s...
it's quite old fashioned, pre-dating modern IDEs.
Log.d("criarArq", gpxfile.toString());
Upvotes: 1