I'm trying to load a JSON from webservice and write it to a file using the following code:
File cacheDir = new File(context.getCacheDir(), "texts");
cacheDir.mkdirs();
File cacheFile = new File(cacheDir, "" + articleId);
try {
if (!cacheFile.exists()) {
try {
HttpURLConnection c = (HttpURLConnection) new URL(url).openConnection();
try {
InputStream in = c.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
// this approach fails
/*
BufferedWriter writer = new BufferedWriter(new FileWriter(cacheFile.getAbsolutePath()));
String line = null;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}
writer.flush();
reader.close();
writer.close();
*/
// this approach works
Gson g = new Gson();
Article article = g.fromJson(reader, Article.class);
String json = g.toJson(article);
PrintWriter out = new PrintWriter(new FileWriter(cacheFile.getAbsolutePath()));
out.print(json);
out.flush();
out.close();
reader.close();
} catch (IOException e) {
Log.e(getClass().getSimpleName(), "Exception parsing JSON", e);
} finally {
c.disconnect();
}
} catch (Exception e) {
Log.e(getClass().getSimpleName(), "Exception parsing JSON", e);
}
}
}
I've checked with adb shell and Android Monitor file browswer and the files seem to be created:

However, when I do cat filename from adata/data/appdir/cache no file content is printed (only command is printed again cat filename). What is wrong with my approach?
GenymotioncacheFile.exists(). Try debugging the content of the reader. Add some log to see if you are getting data back from the server. Do you have the internet permission ?Log.d("TEST", ": " + line)in the while loop and read the output