天天看點

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


}