靈魂-放水

          為學(xué)日益,為道日損。

          BlogJava 首頁 新隨筆 聯(lián)系 聚合 管理
            296 Posts :: 10 Stories :: 274 Comments :: 0 Trackbacks

          <%@page import="java.net.*,java.io.*"%>
          <%!
            public boolean saveUrlAs(String photoUrl, String fileName) {
          //此方法只能用戶HTTP協(xié)議
              try {
                URL url = new URL(photoUrl);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                DataInputStream in = new DataInputStream(connection.getInputStream());
                DataOutputStream out = new DataOutputStream(new FileOutputStream(fileName));
                byte[] buffer = new byte[4096];
                int count = 0;
                while ((count = in.read(buffer)) > 0) {
                  out.write(buffer, 0, count);
                }
                out.close();
                in.close();
                return true;
              }
              catch (Exception e) {
                return false;
              }
            }
           
          public String getDocumentAt(String urlString) {
          //此方法兼容HTTP和FTP協(xié)議
              StringBuffer document = new StringBuffer();
              try {
                URL url = new URL(urlString);
                URLConnection conn = url.openConnection();
                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.
                    getInputStream()));
                String line = null;
                while ( (line = reader.readLine()) != null) {
                  document.append(line + "\n");
                }
                reader.close();
              }
              catch (MalformedURLException e) {
                System.out.println("Unable to connect to URL: " + urlString);
              }
              catch (IOException e) {
                System.out.println("IOException when connecting to URL: " + urlString);
              }
              return document.toString();
            }
          %>
          <%
          //測(cè)試
            String photoUrl = "  String fileName = photoUrl.substring(photoUrl.lastIndexOf("/"));
            String filePath = "d:/ghost/";
            boolean flag = saveUrlAs(photoUrl, filePath + fileName);
            out.println("Run ok!\n<BR>Get URL file " + flag);
          %>


          轉(zhuǎn)賽迪技術(shù)


          Feedback

          # re: [轉(zhuǎn)]從URL獲取文件保存到本地的JAVA代碼 2007-10-11 17:04 老白楊
          請(qǐng)問,兼容HTTP和FTP協(xié)議的getDocumentAt方法,作用是?  回復(fù)  更多評(píng)論
            

          主站蜘蛛池模板: 南召县| 凉山| 疏勒县| 广宗县| 滨海县| 都昌县| 双桥区| 红安县| 湘阴县| 洪泽县| 桦南县| 杂多县| 攀枝花市| 鹤峰县| 芜湖市| 江华| 民丰县| 托克逊县| 甘孜县| 仪征市| 平塘县| 汉沽区| 建阳市| 兴安县| 香港| 汾阳市| 湘乡市| 砚山县| 社会| 赤城县| 新巴尔虎右旗| 彭州市| 长寿区| 正安县| 双流县| 夏邑县| 吉林省| 石家庄市| 略阳县| 筠连县| 新沂市|