[英]Files are created empty when using BufferReader and BufferWriter to write a file
I'm trying to load a JSON from webservice and write it to a file using the following code: 我正在尝试从Web服务加载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);
}
}
}
I've checked with adb shell and Android Monitor file browswer and the files seem to be created: 我检查了adb shell和Android Monitor文件浏览器,发现文件似乎已创建:
However, when I do cat filename
from adata/data/appdir/cache
no file content is printed (only command is printed again cat filename
). 但是,当我从
adata/data/appdir/cache
执行cat filename
,没有文件内容被打印(仅再次打印命令cat filename
)。 What is wrong with my approach? 我的方法有什么问题?
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. 如果路径表示的文件存在,则file.exists()方法返回true。 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
Instead of use readLine
to read from the InputStream, try with read
and a char[]
而不是使用
readLine
从InputStream read
,请尝试使用read
和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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.