http协议下载文件代码:
- public class HttpDownload {
- private final int BUF_SIZE = 8096;
- private String strUrl = null;
- private String localFile = null;
- private String localDir = null;
- private URL url = null;
- private HttpURLConnection httpConn = null;
- private boolean debug = true;
- public HttpDownload() {
- }
- public HttpDownload(String url, String file, String dir) throws IOException {
- strUrl = url;
- localFile = file;
- localDir = dir;
- init();
- }
- private void init() throws IOException {
- url = new URL(strUrl);
- httpConn = (HttpURLConnection)url.openConnection();
- }
- public void download() throws IOException {
- BufferedInputStream bis = null;
- FileOutputStream fos = null;
- int size = 0;
- byte[] buf = new byte[BUF_SIZE];
- httpConn.connect();
- bis = new BufferedInputStream(httpConn.getInputStream());
- fos = new FileOutputStream(localDir + File.separator + localFile);
- if (debug) {
- System.out.println("retreiving the file");
- }
- System.out.println("starting download.");
- while((size = bis.read(buf)) != -1) {
- fos.write(buf, 0, size);
- }
- fos.close();
- bis.close();
- httpConn.disconnect();
- System.out.println("download finish.");
- }
-