采用URL读取网络文件

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class Url {  
    static byte[] SjwGetBuffer(String url) throws IOException {   
        ByteArrayOutputStream  bos  =  new ByteArrayOutputStream();  
        try{  
            URL sjwurl = null;   
            HttpURLConnection httpUrl = null;   
            BufferedInputStream bis = null;   
            byte[] buf = new byte[1024];   
               
            sjwurl = new URL(url);   
            httpUrl = (HttpURLConnection) sjwurl.openConnection();   
            httpUrl.connect();  
            bis = new BufferedInputStream(httpUrl.getInputStream());  
            if(bis==null)return null;  
            while(true)  {   
                int bytes_read = bis.read( buf );   
                if( bytes_read > 0 ) {   
                    bos.write( buf, 0, bytes_read );   
                }else {   
                    break;   
                }   
            } ;   
            bis.close();   
            httpUrl.disconnect();   
        }catch   (Exception e) {     
              System.out.println("err!");   
              return null;  
        }  
        return bos.toByteArray();   
    }   
 
    public static void main(String[] args) throws Exception {  
        byte[] strBuf = SjwGetBuffer("http://www.baidu.com");   
        FileOutputStream fileStream = new FileOutputStream("c:baidu.html");   
        fileStream.write(strBuf);   
        fileStream.close();   
    }
}

阅读更多
个人分类: Java
上一篇mysql错误: Duplicate entry '2' for key 'stateid'
下一篇使用junit4,没有对错条提示,报错信息为nitializationError0
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭