在main函式中實現Servlet下載服務的客戶端
阿新 • • 發佈:2019-01-02
場景:獲取一個url從下載服務端下載檔案到本地路徑
1.本例服務端可以參考, 使用Servlet實現檔案下載服務端
2.本例主要使用java.net.URL,java.net.URLConnection來實現網路連線下載
public class TestDownloadServlet { /**1.本地儲存已經下載的檔案目錄 */ private static final String localPath = "E:\\download\\"; /**2.下載url */ private static final String url = "http://127.0.0.1:8080/study/download?filename=8195B04F2E924C2E9596AC79488351EF.zip"; /**3.需要下載的檔名*/ private static final String fileName = "8195B04F2E924C2E9596AC79488351EF.zip"; public static void main(String[] args) { System.out.println("測試開始....."); try { downloadLocal(url); } catch (IOException e) { e.printStackTrace(); } System.out.println("測試結束....."); } /** 4.建立請求連線並從網路流中讀取資料*/ public static void downloadLocal(String urls) throws IOException { String local = localPath + fileName; URL url = new URL(urls); URLConnection con = url.openConnection(); FileOutputStream out = new FileOutputStream(local); InputStream ins = con.getInputStream(); byte[] b = new byte[1024 * 8]; int i = 0; while ((i = ins.read(b)) != -1) { out.write(b, 0, i); } ins.close(); out.close(); } }
以上,TKS.