我正在从服务器下载一个大尺寸的zip文件.我正在追随
06-11 21:45:18.789: I/System.out(8993): java.net.SocketException: recvfrom failed: ETIMEDOUT (Connection timed out)
Run Code Online (Sandbox Code Playgroud)
我的申请没有停止,但我的下载停止了.这发生在hdpi android mobile专门说低处理器设备上.下载在S3和平板电脑上运行正常.我使用简单的FileOutputStream方法下载文件.
我使用以下代码来限制java中文件的下载速度:
package org;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
class MainClass {
public static void main(String[] args) {
download("https://speed.hetzner.de/100MB.bin");
}
public static void download(String link) {
try {
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(5000);
con.setReadTimeout(5000);
InputStream is = con.getInputStream();
CustomInputStream inputStream = new CustomInputStream(is);
byte[] buffer = new byte[2024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
System.out.println("downloaded : " + len);
//save file
}
} catch (IOException e) {
e.printStackTrace();
} …Run Code Online (Sandbox Code Playgroud) 我想以编程方式限制Java中的上传或下载操作.我会假设我需要做的就是检查上传的速度和插入方式Thread.sleep(),如下所示:
while (file.hasMoreLines()) {
String line = file.readLine();
for (int i = 0; i < line.length(); i+=128) {
outputStream.writeBytes(line.substr(i, i+128).getBytes());
if (isHittingLimit())
Thread.sleep(500);
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码会起作用吗?如果没有,有更好的方法吗?有没有一个描述这个理论的教程?