java.io.FileNotFoundException: http://127.0.0.1/xxxx.jpg

0.码仙励志

孤独是每个强者必须经历的坎。

1.抛出问题

用java下载文件的时候抛出以下异常(部分文件正常,部分文件失败,失败的文件浏览器可以正常解析):

java.io.FileNotFoundException: http://127.0.0.1/xxxx.jpg
	at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1872)
	at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474)

2.解决方案

URL url = new URL(urlString);

改为

URL url = new URL(new URI(urlString).toASCIIString());

完整代码如下:

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;

public class Test {

	public static void download(String urlString, String filename, String savePath) {
		try {
			// URL url = new URL(urlString);
			URL url = new URL(new URI(urlString).toASCIIString());
			URLConnection con = url.openConnection();
			con.setConnectTimeout(5000);
			InputStream is = con.getInputStream();
			byte[] bs = new byte[1024];
			int len;
			File sf = new File(savePath);
			if (!sf.exists()) {
				sf.mkdirs();
			}
			OutputStream os = new FileOutputStream(sf.getPath() + "\\" + filename);
			while ((len = is.read(bs)) != -1) {
				os.write(bs, 0, len);
			}
			os.close();
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		String urlString = "http://127.0.0.1/xxxx.jpg";
		String savePath = "D:\\image";
		String filename = "a.jpg";
		download(urlString, filename, savePath);
	}
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值