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);
}
}