【发布时间】:2020-07-08 08:41:57
【问题描述】:
所以我尝试在我的应用程序中实现https://stackoverflow.com/a/1718140/13592426这个用于下载文件的功能,但我没有成功,并想找出原因。代码如下:
public class Receiver extends BroadcastReceiver {
public static void downloadFile(String url, File outputFile) {
try {
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
DataOutputStream fos = new DataOutputStream(new FileOutputStream(outputFile));
fos.write(buffer);
fos.flush();
fos.close();
} catch(FileNotFoundException e) {
Log.i("FileNotFoundException", "file not found"); // swallow a 404
} catch (IOException e) {
Log.i("IOException", "io exc"); // swallow a 404
}
}
Handler handler;
@Override
public void onReceive(Context context, Intent intent) {
final String link = "https://images.app.goo.gl/zjcreNXUrrihcWnD6";
String path = Environment.getExternalStorageDirectory().toString()+ "/Downloads";
final File empty_file = new File(path);
new Thread(new Runnable() {
@Override
public void run() {
downloadFile(link, empty_file);
}
}).start();
}
}
我得到了这些错误:
2020-07-07 14:09:23.142 26313-26371/com.example.downloader E/AndroidRuntime: FATAL EXCEPTION: Thread-2
Process: com.example.downloader, PID: 26313
java.lang.NegativeArraySizeException: -1
at com.example.downloader.Receiver.downloadFile(Receiver.java:39)
at com.example.downloader.Receiver$1.run(Receiver.java:66)
at java.lang.Thread.run(Thread.java:919)
第 39 行是:
byte[] buffer = new byte[contentLength];
也许主要的问题在于线程的错误使用。
老实说,我是 Android 新手,很难解决这个问题,也许你可以推荐一些与 Android 中的线程/URL 相关的好材料或教程(我已经搜索了很多,但仍然很难)。当然,对于我做错了什么,我会很感激直接的建议。
【问题讨论】:
标签: java android multithreading urlconnection