Reputation: 105497
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?
Upvotes: 1
Views: 97
Reputation: 157457
Instead of use readLine
to read from the InputStream, try with read
and a char[]
if (in != null) {
StringBuffer stringBuffer = new StringBuffer();
final char[] charBuffer = new char[8 * 1024];
reader = new BufferedReader(new InputStreamReader(in), charBuffer.length);
int read;
while ((read = reader.read(charBuffer)) != -1) {
stringBuffer.append(charBuffer, 0, read);
}
PrintWriter out = new PrintWriter(new FileWriter(cacheFile.getAbsolutePath()));
out.print(stringBuffer.toString());
out.flush();
out.close();
reader.close();
Gson g = new Gson();
Article article = g.fromJson(stringBuffer.toString(), Article.class);
}
Upvotes: 1
Reputation: 1256
You are doing all the operations inside
if (!cacheFile.exists()) {
//your code here
}
The file.exists() method returns true if a file denoted by the path exists. So in effect what you are saying is 'do my operations if the file does not exist' which does not make sense.
Instead you could
if (!cacheFile.exists()) {
cacheFile.createNewFile()
}
//do the rest of your stuff here
Upvotes: 1