繁体   English   中英

如何将下载的文件保存到我的应用程序中以供以后使用?

[英]How do I save downloaded files to my app for later use?

我的应用程序使用API​​将数据保存到数据库。 该数据的一部分将包含文件(pdf,图像和视频)的网址。 我已经通过AsyncTask执行此api请求。

我的计划是使用api提供的网址->将文件保存在本地->将其位置存储在数据库中。

这样,我可以基于一组SQLite参数调用pdf文档列表,获取文件信息,创建文件列表,并允许用户查看pdf(或图像...或视频...)。 )进行选择。

我一切正常,但不确定如何

  1. 从URL下拉文件
  2. 本地保存文件
  3. 将当前保存的文件位置保存到数据库

我知道这是一个很大的问题,我正在寻找有关如何实现此目标的良好资源。 有很多资源,但是选择最佳选项是压倒性的。

谢谢!

-----编辑-----

使用Zygote的答案后出现错误:

java.io.FileNotFoundException: /storage/emulated/0/library/2/invester-service.jpg: open failed: ENOENT (No such file or directory)
    at libcore.io.IoBridge.open(IoBridge.java:416)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:88)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:73)
    at com.myBooks.library.BooksDB$1.run(BooksDB.java:812)
    at java.lang.Thread.run(Thread.java:856)
Caused by: libcore.io.ErrnoException: open failed: ENOENT (No such file or directory)
    at libcore.io.Posix.open(Native Method)
    at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
    at libcore.io.IoBridge.open(IoBridge.java:400)

我可以看到错误中显示了第812行(显示809-812):

File file = new File(SDCardRoot + "/library/"+file_type,file_name);

//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);

我添加了代码来创建目录(根据Zygote的建议),但是我遇到了同样的错误。 mkdir失败,并且运行时存储状态显示为已挂载:

File folder = new File(Environment.getExternalStorageDirectory() + "/library/"+file_type);
String state = Environment.getExternalStorageState();
//create a new file, specifying the path, and the filename
//which we want to save the file as.

boolean success = true;
if (!folder.exists()) {
    success = folder.mkdir();
    Log.d("storage state",state);
}
if (success) {
    // Do something on success
    Log.d("success","made it");
} else {
    // Do something else on failure 
    Log.d("success","didn't made it");
}

它实际上相当简单。 您只需使用HttpURLConnection以及输入和输出流来下载文件并将其保存到您想要的任何位置,就可以完成1和2。 然后只需在数据库类中添加一个方法即可将文件保存到的位置存储在数据库中。

前一段时间我写了一个非常简单的文件下载应用程序,其中包含任务一和任务二所需的所有代码。 在这里复制/粘贴太多了,所以我只给您发送GitHub源链接。 这里查看第102行及以下

请记住,永远不要在您的GUI线程上运行网络代码!

祝好运!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM