【www.bbyears.com--js教程】
packagecom.github.pandafang.tool; importjava.io.BufferedOutputStream; importjava.io.File; importjava.io.FileOutputStream; importjava.io.IOException; importjava.io.InputStream; importjava.net.URL; importjava.nio.channels.Channels; importjava.nio.channels.FileChannel; importjava.nio.channels.ReadableByteChannel; importjava.nio.file.Files; importjava.nio.file.Path; importjava.nio.file.Paths; importjava.nio.file.StandardCopyOption; importorg.apache.commons.io.FileUtils; /** * 文件工具类 * @author panda fang * @date 2017-08-26 * @version 1.0 */ publicclassFileTool { /** * 使用传统io stream 下载文件 * @param url * @param saveDir * @param fileName */ publicstaticvoiddownload(String url, String saveDir, String fileName) { BufferedOutputStream bos =null; InputStream is =null; try{ byte[] buff =newbyte[8192]; is =newURL(url).openStream(); File file =newFile(saveDir, fileName); file.getParentFile().mkdirs(); bos =newBufferedOutputStream(newFileOutputStream(file)); intcount =0; while( (count = is.read(buff)) != -1) { bos.write(buff,0, count); } } catch(IOException e) { e.printStackTrace(); } finally{ if(is !=null) { try{ is.close(); }catch(IOException e) { e.printStackTrace(); } } if(bos !=null) { try{ bos.close(); }catch(IOException e) { e.printStackTrace(); } } } } /** * 利用 commonio 库下载文件,依赖Apache Common IO ,官网 https://commons.apache.org/proper/commons-io/ * @param url * @param saveDir * @param fileName */ publicstaticvoiddownloadByApacheCommonIO(String url, String saveDir, String fileName) { try{ FileUtils.copyURLToFile(newURL(url),newFile(saveDir, fileName)); }catch(IOException e) { e.printStackTrace(); } } /** * 使用NIO下载文件, 需要 jdk 1.4+ * @param url * @param saveDir * @param fileName */ publicstaticvoiddownloadByNIO(String url, String saveDir, String fileName) { ReadableByteChannel rbc =null; FileOutputStream fos =null; FileChannel foutc =null; try{ rbc = Channels.newChannel(newURL(url).openStream()); File file =newFile(saveDir, fileName); file.getParentFile().mkdirs(); fos =newFileOutputStream(file); foutc = fos.getChannel(); foutc.transferFrom(rbc,0, Long.MAX_VALUE); }catch(IOException e) { e.printStackTrace(); }finally{ if(rbc !=null) { try{ rbc.close(); }catch(IOException e) { e.printStackTrace(); } } if(foutc !=null) { try{ foutc.close(); }catch(IOException e) { e.printStackTrace(); } } } } /** * 使用NIO下载文件, 需要 jdk 1.7+ * @param url * @param saveDir * @param fileName */ publicstaticvoiddownloadByNIO2(String url, String saveDir, String fileName) { try(InputStream ins =newURL(url).openStream()) { Path target = Paths.get(saveDir, fileName); Files.createDirectories(target.getParent()); Files.copy(ins, target, StandardCopyOption.REPLACE_EXISTING); }catch(IOException e) { e.printStackTrace(); } } }
下载一个百度logo 测试一下
publicstaticvoidmain(String[] args) { FileTool.downloadByNIO2("http://www.baidu.com/img/bd_logo1.png","/home/panda/picture","baidu_logo.png"); System.out.println("done..."); }