有两种方法,一种是从服务器下载文件,然后将其写入设备的内存。使用 Fetch 库。第二种方法是读取文件。我不明白我的错误 - 正在创建文件,但是在读取它时,它给出了“”。根据日志,下载正常进行。
private void BookLoader(int bookId) {
String bookIdJson = "http://****.ru/todbook/book" + bookId + ".json";
Fetch bFetch;
String folderJsB = getApplicationContext().getFilesDir().getPath();
String fileName = "list_"+Uri.parse(bookIdJson).getLastPathSegment();
Request request = new Request(bookIdJson, folderJsB, fileName);
bFetch = Fetch.newInstance(getApplicationContext());
bFetch.removeRequests();
long resD = bFetch.enqueue(request);
resD = 0;
}
这是读取方法代码
private String GetJson(String fileListBook) {
try {
File f = new File(getApplicationContext().getFilesDir().getPath() + "/" + fileListBook);
//check whether file exists
if(!f.exists()){
return null;
}
FileInputStream is = new FileInputStream(f);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
return new String(buffer);
} catch (IOException e) {
Log.e("TAG", "Error in Reading: " + e.getLocalizedMessage());
return null;
}
}
尝试使用此方法读取文件:
读取文件最简单的方法是: