您的位置:首页 > 编程语言 > Java开发

Java 通过URL地址下载文本内容到本地文件中

2017-10-09 21:46 846 查看
HTTP传输协议过程中,HTTP服务器在每个响应前面的首部中提供了大量信息,例如,下面一个Apache Web服务器返回的一个典型的HTTP首部:


通过URL进行资源下载时,创立连接,使用getContentType()确定文本类别,比如只下载txt文件,我们将指定非Content-Type里面非text文件,抛出异常。然后通过getContentLength()获取文本大小,通过IO流将文本内容保存到本地指定文件内。

代码如下:

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class BinarySaver {

private final static String url = "地址";

public static void main(String[] args) {
try {
URL root = new URL(url);
saveBinary(root);
} catch (MalformedURLException e) {
// TODO: handle exception
System.out.println(url + "is not URL");
} catch (IOException e) {
// TODO: handle exception
System.out.println(e);
}
}

public static void saveBinary(URL u) throws IOException {
// TODO Auto-generated method stub
URLConnection uc = u.openConnection();
String contentType = uc.getContentType();
int contentLength = uc.getContentLength();
/*
* 可以限制不下载哪种文本文件
if (contentType.startsWith("text/") || contentLength == -1) {
throw new IOException("This is not a binary file.");
}*/

try (InputStream raw = uc.getInputStream()) {
InputStream in = new BufferedInputStream(raw);
byte[] data = new byte[contentLength];
int offset = 0;
while (offset < contentLength) {
int bytesRead = in.read(data, offset, data.length - offset);
if (bytesRead == -1) {
break;
}
offset += bytesRead;
}

if (offset != contentLength) {
throw new IOException("Only read " + offset
+ " bytes; Expected " + contentLength + " bytes");
}
String filename = "存储位置";
try (FileOutputStream fout = new FileOutputStream(filename)) {
fout.write(data);
fout.flush();
}
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java