[英]using Java to download file
我正在尝试从该URL下载文件,但是代码挂在getInputStream();上。 我在浏览器中键入此URL。 该URL可访问http://filehost.blob.core.windows.net/firmware/version.txt
是什么原因造成的?
URL url = new URL("http://filehost.blob.core.windows.net/firmware/version.txt");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream(); //hang at this line
int totalSize = urlConnection.getContentLength();
解
将URL
与Scanner
一起使用。
码
URL url = new URL("http://filehost.blob.core.windows.net/firmware/version.txt");
Scanner s = new Scanner(url.openStream());
while (s.hasNextLine())
System.out.println(s.nextLine());
s.close();
OUTPUT
1.016
注意
必须thrown
或处理MalformedURLException
和IOException
。
解
使用JAVA NIO 。
码
URL website = new URL("http://filehost.blob.core.windows.net/firmware/version.txt");
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream("C:/temp/version.txt");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
OUTPUT
文件已在c:\\test\\version.txt
创建,大小为5个字节
注意
必须thrown
或处理MalformedURLException
, FileNotFoundException
和IOException
。
我尝试了您的代码段,但无法重现您的问题-它对我来说不可行。 我认为您的网络(配置)可能存在一些问题,并且您的代码将挂起,直到发生超时。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.