我試圖從我的應用程序中下載文件。我設置了一個按鈕的onClickListener調用這個方法:試圖從Android應用程序內下載文件
private void downloadFile(String fileUrl, File destDir, String fileName) {
try {
URL url = new URL(fileUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.connect();
if (destDir.isDirectory() && !destDir.exists()) {
destDir.mkdirs();
}
FileOutputStream output = new FileOutputStream(new File(destDir.toString() + "/" + fileName));
InputStream input = connection.getInputStream();
byte[] buffer = new byte[1024];
int byteCount = 0;
while ((byteCount = input.read(buffer)) != -1) {
output.write(buffer, 0, byteCount);
}
output.close();
input.close();
} catch (IOException e) {
Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
Log.e("IOException", "Error: " + e.getMessage(), e);
} finally {
Toast.makeText(this, "File downloaded: " + fileName, Toast.LENGTH_SHORT).show();
}
}
我已經經歷各種主題,但沒有一個似乎想出了一個可用的解決方案。當我使用上面指定的代碼時,似乎沒有任何事情發生。
編輯:該文件將在後臺下載並在完成時顯示一個簡短的祝酒。雖然下載時按鈕似乎被「點擊」。對此有何想法?
感謝您的幫助!
其實我並不需要所有的代碼。我不得不使用類似這樣的:
private void getFile(String url) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
Log.e("ActivityNotFoundException", "Error: " + e.getMessage(), e);
} catch (NullPointerException e) {
Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
Log.e("NullPointerException", "Error: " + e.getMessage(), e);
}
}
這也應該是有益的一些人:
private void openFile(File file) {
try {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.fromFile(file));
intent.addCategory(Intent.CATEGORY_BROWSABLE);
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
Log.e("ActivityNotFoundException", "Error: " + e.getMessage(), e);
} catch (NullPointerException e) {
Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
Log.e("NullPointerException", "Error: " + e.getMessage(), e);
}
}
什麼是你的問題? – someUser