用java实现文件的下载,如何提高下载速度(非web开发)
2个回答
展开全部
下面贴出的代码是一个简单的读取远程文件保存到本地的实现,至于提高下载速度你可以利用多线程,具体可参考最下面的那个网址——
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
public class DownloadTester {
public static void main(String[] args) throws IOException {
String urlStr = "https://gss0.bdstatic.com/70cFsjip0QIZ8tyhnq/img/logo-zhidao.gif";
String path = "D:/";
String name = urlStr.substring(urlStr.trim().lastIndexOf("/"));
URL url = new URL(urlStr);
InputStream in = url.openConnection().getInputStream();
File file = new File(path + name);
FileOutputStream out = new FileOutputStream(file, true);
int counter = 0;
int ch;
byte[] buffer = new byte[1024];
while ((ch = in.read(buffer)) != -1) {
out.write(buffer, 0, ch);
counter += ch;
System.out.println(counter + ":byte");
}
out.flush();
in.close();
out.close();
}
}
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
public class DownloadTester {
public static void main(String[] args) throws IOException {
String urlStr = "https://gss0.bdstatic.com/70cFsjip0QIZ8tyhnq/img/logo-zhidao.gif";
String path = "D:/";
String name = urlStr.substring(urlStr.trim().lastIndexOf("/"));
URL url = new URL(urlStr);
InputStream in = url.openConnection().getInputStream();
File file = new File(path + name);
FileOutputStream out = new FileOutputStream(file, true);
int counter = 0;
int ch;
byte[] buffer = new byte[1024];
while ((ch = in.read(buffer)) != -1) {
out.write(buffer, 0, ch);
counter += ch;
System.out.println(counter + ":byte");
}
out.flush();
in.close();
out.close();
}
}
参考资料: http://hi.baidu.com/zhizhesky/blog/item/f86c32db66f5c36dd0164edf.html
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |