java获取远程文件(保证文件的完整性,不会出现无法打开的情况)

来源:互联网 发布:阿里云服务器怎么镜像 编辑:程序博客网 时间:2024/06/06 07:25
package com.shu.example;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileOutputStream;import java.net.HttpURLConnection;import java.net.URL;public class FileUtil {/** * 获取远程文件 * @param remoteFilePath 远程文件路径 * @param localFilePath 本地文件路径 */public void getFile(String remoteFilePath,String localFilePath){URL urlfile = null; HttpURLConnection httpUrl = null; BufferedInputStream bis = null; BufferedOutputStream bos = null; File f = new File(localFilePath);/*//如果需要设置代理时String proxy = "192.168.224.12";String port = "8080";Properties systemProperties = System.getProperties();systemProperties.setProperty("http.proxyHost",proxy);systemProperties.setProperty("http.proxyPort",port);*/try{ urlfile = new URL(remoteFilePath); httpUrl = (HttpURLConnection)urlfile.openConnection(); httpUrl.connect(); bis = new BufferedInputStream(httpUrl.getInputStream());bos = new BufferedOutputStream(new FileOutputStream(f));int len=2048;byte[] b = new byte[len]; while((len=bis.read(b))!=-1) { bos.write(b, 0, len);}bos.flush(); bis.close();httpUrl.disconnect();System.out.println("done~");}catch(Exception e){ } }}