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

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

HTTP传输协议过程中,HTTP服务器在每个响应前面的首部中提供了大量信息,例如,下面一个Apache Web服务器返回的一个典型的HTTP首部:这里写图片描述 通过URL进行资源下载时,创立连接,使用getContentType()确定文本类别,比如只下载txt文件,我们将指定非Content-Type里面非text文件,抛出异常。然后通过getContentLength()获取文本大小,通过IO流将文本内容保存到本地指定文件内。 代码如下:

// An highlighted block
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();
            }
        }
    }


}

猜你喜欢

转载自blog.csdn.net/bwt1989/article/details/83280871