import java.io.*; import java.net.HttpURLConnection; import java.net.URL; public class DownLoadFile { private static DownLoadFile instance = null; private DownLoadFile(){}; public static DownLoadFile getInstance() { if (null == instance) { instance = new DownLoadFile(); } return instance; } public void doDownLoad(String remoteFilePath, String localFilePath) { URL urlfile = null; HttpURLConnection httpUrl = null; BufferedInputStream bis = null; BufferedOutputStream bos = null; File f = new File(localFilePath); try { String dir = f.getParent(); File fdir = new File(dir); if (!fdir.exists()) { fdir.mkdirs(); } if(!f.exists()){//判断文件是否真正存在,如果不存在,创建一个; f.createNewFile(); } urlfile = new URL(remoteFilePath); httpUrl = (HttpURLConnection)urlfile.openConnection(); httpUrl.connect(); bis = new BufferedInputStream(httpUrl.getInputStream()); bos = new BufferedOutputStream(new FileOutputStream(f)); byte[] buff = new byte[1024]; //Receive the file, write it out. int data; while ( -1 != ( data = bis.read(buff) ) ) { bos.write( buff,0,data ); } bos.flush(); bis.close(); httpUrl.disconnect(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != bis) bis.close(); if (null != bos) bos.close(); } catch (IOException e) { e.printStackTrace(); } } } }
514total visits,1visits today
Leave a Reply