我正在尝试从webservice加载JSON并使用以下代码将其写入文件:
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);
}
}
}
我已经检查了adb shell和Android Monitor文件browswer并且似乎创建了文件:
但是,当我cat filename
adata/data/appdir/cache
时,不会打印任何文件内容(只会再次打印命令cat filename
)。我的方法出了什么问题?
答案 0 :(得分:1)
您正在进行
内的所有操作if (!cacheFile.exists()) {
//your code here
}
如果路径表示的文件存在,则file.exists()方法返回true。因此,实际上你所说的是如果文件不存在则执行我的操作'没有意义。
相反,你可以
if (!cacheFile.exists()) {
cacheFile.createNewFile()
}
//do the rest of your stuff here
答案 1 :(得分:1)
尝试使用String path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
和readLine
read
来读取InputStream
char[]