獲取遠程服務器的文件輸入流(在已知文件存放位置的情況下)

注意橙色部分,要寫客戶端程序橙色部分大體不變,存儲部分就要根據情況改動,不改肯定達不到效果

 

import java.net.URL;

import java.net.HttpURLConnection;

import java.io.*;

import java.lang.*;

import java.util.*;

 

 //文件名;
 String filename = "xxxxxx.xxx";
 //遠程文件路徑的位置;
 String filepath = "http://www.xxxx.com/xxxx/" + filename;

 //創建url;
 URL url = new URL(filepath);
 //創建url連接;
    HttpURLConnection urlconn = (HttpURLConnection)url.openConnection();
 //鏈接遠程服務器;
    urlconn.connect();

BufferedInputStream  bis = null;
ServletOutputStream os =null;

//BufferedOutputStream   bos   =   null;
 try{
  
   //獲取遠程服務器端文件輸入流;
   bis = new BufferedInputStream(urlconn.getInputStream() );

   os = response.getOutputStream();

   // bos   =  new   BufferedOutputStream(response.getOutputStream());   
   //緩存;  
    byte b[]=new byte[2048];    
   //客戶使用保存文件的對話框:   
   response.setHeader("Content-disposition","inline;filename="+filename);
   //通知客戶文件的MIME類型:   
   response.setContentType("application/octet-stream exe;charset=gb2312");   
   
   int size;
   //讀取文件內容到緩存;
   while((size=bis.read(b,0,b.length))!=-1)   
   {   //把文件內容寫到本地文件中;
   //bos.write(b,0,size);   
    os.write(b,0,size);
   }

  }catch (Exception e) {
  
   e.printStackTrace();
  }finally{
  
   if(fos != null)
   { //關閉文件輸出流;
    fos.close();
   }
   if(bis != null)
   { //關閉文件輸入流;
    bis.close();
    urlconn.disconnect();
   }
  }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章