我需要从互联网下载文件并在Android Studio片段中读取其文本内容
我已经设法通过下载管理器下载文件,但是无法访问和读取文件。
File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
String downloadPath = dir.getAbsolutePath();
String path = downloadPath + "/" + fileName;
DownloadManager dm;
dm = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(pdfLink);
DownloadManager.Request request = new DownloadManager.Request(uri);
//request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setTitle(fileName);
//it crushes at this line below
request.setDestinationInExternalPublicDir(downloadPath, fileName);
Long reference = dm.enqueue(request);
request.setDestinationInExternalPublicDir(downloadPath, fileName);
我尝试了这段代码来读取它,但是如果我插入随机输入(例如“ ashdbas”),则在插入文件路径时应用程序会崩溃,尽管它什么也不会读取*但不会崩溃。
int ch;
StringBuilder str=new StringBuilder();
try {
FileInputStream fis = getActivity().openFileInput(path);
try {
while ((ch=fis.read())!=-1)
str.append((char)ch);
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//convert to string
String s=str.toString();
这是我要下载的文件:https://docs.google.com/document/d/1ALWFQ57sB7mdcI5zN6s_6_7hQfKR-B8KgQfN2aK8kbI/edit?usp=sharing
另外,我注意到下载文件夹中充满了具有相同名称的文件,它们之间应该没有任何区别吗?