赞
踩
目录
- /**
- * URL
- * 类 URL 代表一个统一资源定位符,它是指向互联网“资源”的指针。
- * 抓取文件:以下载一张图片为例
- * 1、创建URL对象 指定文件的URL地址(图片的URL地址)
- * 2、获取远程连接的对象
- * 3、设置获取方式,一般用到GET、POST方式
- * 4、获取HTTP响应的状态码 200表示请求成功
- * 5、字节输入流 读取文件
- * 6、字节输出流 把读取的文件存入本地
- * @author hw
- *
- */
- ---------------------
-
- public class TestDowload {
- public static void main(String[] args) {
- BufferedInputStream bufferedInputStream = null;
- BufferedOutputStream bufferedOutputStream = null;
-
-
- try {
- URL url = new URL("https://e-cloudstore.com/files/ecology_dev.zip");
- HttpURLConnection conn=(HttpURLConnection)url.openConnection();
- conn.setRequestMethod("GET");
- //设置URL请求方式 GET方式
- conn.setRequestMethod("GET");
- //从HTTP响应消息获取状态码
- int code=conn.getResponseCode();
- //如果状态码为200表示请求成功
- if(code ==200){
- bufferedInputStream = new BufferedInputStream(conn.getInputStream());
- bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("D://ecology_dev.zip"));
-
-
- byte[] by=new byte[1024];
- int len=0;
- while((len=bufferedInputStream.read(by))!=-1) {
- bufferedOutputStream.write(by, 0, len);
- //刷新
- bufferedOutputStream.flush();
- }
- }
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- bufferedInputStream.close();
- bufferedOutputStream.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- }
- }
- public class TestDowload {
- public static void main(String[] args) {
- FileInputStream fileInputStream = null;
- BufferedInputStream bufferedInputStream = null;
- FileOutputStream fileOutputStream = null;
- BufferedOutputStream bufferedOutputStream = null;
-
-
- try {
- fileInputStream = new FileInputStream(new File("d://xxx.txt"));
- bufferedInputStream = new BufferedInputStream(fileInputStream);
-
- fileOutputStream = new FileOutputStream(new File("D:/开发文档/txt"));
- bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
-
- int tag;
- while ((tag = (bufferedInputStream.read())) != -1) {
- bufferedOutputStream.write(tag);
- }
- bufferedOutputStream.flush();
-
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- if (fileInputStream!=null){
- try {
- fileInputStream.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- if (fileOutputStream!=null){
- try {
- fileOutputStream.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- if (bufferedInputStream!=null){
- try {
- bufferedInputStream.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- if (bufferedOutputStream!=null){
- try {
- bufferedOutputStream.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
-
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。