gpt4 book ai didi

android - 如何下载文件并存入sdcard?

转载 作者:太空狗 更新时间:2023-10-29 12:41:54 25 4
gpt4 key购买 nike

我正在研究它应该从服务器下载文件并将其存储在 sdcard 中。

但我得到异常:java.io.filenotfoundexception (permission denied)

public class MainActivity extends ActionBarActivity {


// usually, subclasses of AsyncTask are declared inside the activity class.
// that way, you can easily modify the UI thread from here
private class DownloadTask extends AsyncTask<String, Integer, String> {

private Context context;
private PowerManager.WakeLock mWakeLock;
File file,sdcard;
public DownloadTask(Context context) {
this.context = context;
}

@Override
protected String doInBackground(String... sUrl) {

System.out.print("BAckground");
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();

// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}

// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();

// download the file
input = connection.getInputStream(); '



GEtting exception in line '
output = new FileOutputStream("sdcard/file.mp3");



byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}

if (connection != null)
connection.disconnect();
}
return null;
}

最佳答案

试试这个

File root = new File(Environment.getExternalStorageDirectory(), "file.mp3");
if (!root.exists()) {
root.mkdirs();
}
output = new FileOutputStream(root);

并添加对 list 文件的权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

关于android - 如何下载文件并存入sdcard?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24422043/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com