使用Java下载文件
我试图从这个url下载一个文件,但代码挂起在getInputStream(); 我在浏览器中键入此url。url是可访问的 原因是什么使用Java下载文件,java,azure,Java,Azure,我试图从这个url下载一个文件,但代码挂起在getInputStream(); 我在浏览器中键入此url。url是可访问的 原因是什么 URL url = new URL("http://filehost.blob.core.windows.net/firmware/version.txt"); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setReques
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
与扫描仪一起使用
代码
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();
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();
输出
1.016
注意
必须抛出或处理格式错误的异常
和IOException
下载文件
解决方案
使用
代码
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();
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();
输出
文件已在c:\test\version.txt
创建,大小为5字节
注意
格式错误的异常
,FileNotFoundException
和IOException
必须被抛出或处理。我尝试了你的代码片段,但无法重现你的问题-我没有挂起它。我认为您的网络(配置)可能有一些问题,您的代码会一直挂起,直到出现超时。答案中有很多大写字母!!有两种解决方案分为两部分。。。我过去常常澄清