Java 从网上下载文件的几种方式实例代码详解
废话不多说了,直接给大家贴代码了,具体代码如下所示;
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;
/**
*文件工具类
*@authorpandafang
*@date2017-08-26
*@version1.0
*/
publicclassFileTool{
/**
*使用传统iostream下载文件
*@paramurl
*@paramsaveDir
*@paramfileName
*/
publicstaticvoiddownload(Stringurl,StringsaveDir,StringfileName){
BufferedOutputStreambos=null;
InputStreamis=null;
try{
byte[]buff=newbyte[8192];
is=newURL(url).openStream();
Filefile=newFile(saveDir,fileName);
file.getParentFile().mkdirs();
bos=newBufferedOutputStream(newFileOutputStream(file));
intcount=0;
while((count=is.read(buff))!=-1){
bos.write(buff,0,count);
}
}
catch(IOExceptione){
e.printStackTrace();
}
finally{
if(is!=null){
try{
is.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
if(bos!=null){
try{
bos.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
}
/**
*利用commonio库下载文件,依赖ApacheCommonIO,官网https://commons.apache.org/proper/commons-io/
*@paramurl
*@paramsaveDir
*@paramfileName
*/
publicstaticvoiddownloadByApacheCommonIO(Stringurl,StringsaveDir,StringfileName){
try{
FileUtils.copyURLToFile(newURL(url),newFile(saveDir,fileName));
}catch(IOExceptione){
e.printStackTrace();
}
}
/**
*使用NIO下载文件,需要jdk1.4+
*@paramurl
*@paramsaveDir
*@paramfileName
*/
publicstaticvoiddownloadByNIO(Stringurl,StringsaveDir,StringfileName){
ReadableByteChannelrbc=null;
FileOutputStreamfos=null;
FileChannelfoutc=null;
try{
rbc=Channels.newChannel(newURL(url).openStream());
Filefile=newFile(saveDir,fileName);
file.getParentFile().mkdirs();
fos=newFileOutputStream(file);
foutc=fos.getChannel();
foutc.transferFrom(rbc,0,Long.MAX_VALUE);
}catch(IOExceptione){
e.printStackTrace();
}finally{
if(rbc!=null){
try{
rbc.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
if(foutc!=null){
try{
foutc.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
}
/**
*使用NIO下载文件,需要jdk1.7+
*@paramurl
*@paramsaveDir
*@paramfileName
*/
publicstaticvoiddownloadByNIO2(Stringurl,StringsaveDir,StringfileName){
try(InputStreamins=newURL(url).openStream()){
Pathtarget=Paths.get(saveDir,fileName);
Files.createDirectories(target.getParent());
Files.copy(ins,target,StandardCopyOption.REPLACE_EXISTING);
}catch(IOExceptione){
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...");
}
总结
以上所述是小编给大家介绍的Java从网上下载文件的几种方式实例代码详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!