繁体   English   中英

使用Java下载文件

[英]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();

读取文件内容


URLScanner一起使用。


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或处理MalformedURLExceptionIOException

下载文件


使用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或处理MalformedURLExceptionFileNotFoundExceptionIOException

我尝试了您的代码段,但无法重现您的问题-它对我来说不可行。 我认为您的网络(配置)可能存在一些问题,并且您的代码将挂起,直到发生超时。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM