我使用下载管理器类下载了一个文本文件,下载该文件的代码是:
private long enqueue
private DownloadManager dm;
String server_ip = "http://192.168.0.1/";
Request request = new Request(Uri.parse(server_ip + "test.txt"));
// Store to common external storage:
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "test.txt");
enqueue = dm.enqueue(request);
我有一个广播接收器来检查下载是否成功。如果下载成功,我将尝试在文本中显示txt文件查看:
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
Query query = new Query();
query.setFilterById(enqueue);
Cursor c = dm.query(query);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
// Check if the download is successful
if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
// Get the downloaded file and display the test.txt in a textView
File file = new File(storage_directory,"test.txt");
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('n');
}
br.close();
TextView tv = (TextView)findViewById(R.id.textView);
tv.setText(text);
}
catch (Exception e) {
//You'll need to add proper error handling here
}
}
}
}
}
}
我发现的一个问题是,如果已经有一个文件名相同的文件,"text.txt",设备会将新下载的文件重命名为"text-1.txt"。因此,当我尝试显示新下载文件时,它会显示旧的"test.txt"文件。我想问一下,当下载成功时,我如何引用新文件,而不是像我所做的那样指定文件名:
File file = new File(storage_directory,"test.txt");
此外,我已将文件下载到外部存储器。我知道如果我没有添加这行:
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "test.txt");
当我将请求发送到下载管理器时,文件将被加载到内部存储器。在这种情况下,我该如何查阅文件?
非常感谢。
更新:如果我在广播接收器中成功接收到文件后添加此行:
String uriString = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
uriString给我
file:///storage/emulated/0/Download/test.txt
经过多次尝试,我找到了解决问题的方法。我不知道这是否是一个好的解决方案,但它似乎有效。我添加了以下代码后,它在广播接收器中成功接收到文件,即我添加:
int filenameIndex = c.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME);
String filename = c.getString(filenameIndex);
File file = new File(filename);
并删除了这个代码:
File file = new File(storage_directory,"test.txt");
之后:
if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
通过这样做,它将引用新下载的文件,即使系统重命名了该文件。