隨筆 - 3, 文章 - 0, 評論 - 9, 引用 - 0
          數據加載中……

          2006年8月14日

          java應用程序從網上下載文件

          java應用程序與網絡通訊一直是我的弱項,想補一補,就從這一篇開始吧!
          以從網上下載一個圖象為例:

          import ?java.io.BufferedInputStream;
          import ?java.io.BufferedOutputStream;
          import ?java.io.File;
          import ?java.io.FileOutputStream;
          import ?java.io.IOException;
          import ?java.net.URL;
          import ?java.net.URLConnection;

          public ? class ?DownloadFormURL?{

          ????
          public ? static ? void ?main(String[]?args)?{
          ????????
          try ?{
          ????????????
          new ?DownloadFormURL().downloadFile( " http://127.0.0.1:8080/image/f.jpg " ,? new ?File( " F:/image.jpg " ));
          ????????}?
          catch ?(IOException?e)?{
          ????????????e.printStackTrace();
          ????????}
          ????}

          ????
          public ? void ?downloadFile(String?sourceURL,?File?targetFile)? throws ?IOException?{

          ????????URL?url?
          = ? new ?URL(sourceURL);
          ????????URLConnection?connection?
          = ?url.openConnection();
          ????????java.io.InputStream?inputStream?
          = ?connection.getInputStream();
          ????????FileOutputStream?outputStream?
          = ? new ?FileOutputStream(targetFile);
          ????????BufferedInputStream?in?
          = ? null ;
          ????????BufferedOutputStream?out?
          = ? null ;
          ????????
          byte ?buffer[]? = ? new ? byte [ 8192 ];
          ????????
          try ?{
          ????????????in?
          = ? new ?BufferedInputStream(inputStream,?buffer.length);
          ????????????out?
          = ? new ?BufferedOutputStream(outputStream,?buffer.length);
          ????????????
          int ?total? = ? 0 ;
          ????????????
          for ?( int ?bytesRead? = ? 0 ;?(bytesRead? = ?in.read(buffer))? != ? - 1 ;)?{
          ????????????????out.write(buffer,?
          0 ,?bytesRead);
          ????????????????total?
          += ?bytesRead;
          ????????????}

          ????????}?
          finally ?{
          ????????????in.close();
          ????????????out.close();
          ????????}
          ????????
          return ;
          ????}
          }


          小試了一下,還不錯!

          posted @ 2006-08-14 09:03 nick 閱讀(1729) | 評論 (6)編輯 收藏

          主站蜘蛛池模板: 长阳| 宁南县| 科技| 右玉县| 夏津县| 虞城县| 云和县| 海林市| 绥芬河市| 南部县| 子洲县| 永康市| 义乌市| 沈丘县| 婺源县| 永定县| 徐州市| 安福县| 崇义县| 兰溪市| 藁城市| 杭锦后旗| 周宁县| 昌平区| 洛南县| 兰溪市| 雅安市| 淮南市| 梓潼县| 敖汉旗| 宣恩县| 夏河县| 阜新市| 灵宝市| 甘谷县| 临洮县| 林西县| 克什克腾旗| 青冈县| 外汇| 长阳|