志在指尖
用双手敲打未来

java下载文件到本地实现方法

java下载文件到本地实现方法

packagetestOne;
importjava.io.BufferedWriter;
importjava.io.File;
importjava.io.FileOutputStream;
importjava.io.FileWriter;
importjava.io.IOException;
importjava.io.InputStream;
importjava.net.MalformedURLException;
importjava.net.URL;
importjava.net.URLConnection;
publicclasstestone{
publicstaticvoidmain(String[]args)throwsMalformedURLException{
//要确保下面这个下载地址可以正常访问
StringurlPath=”http://192.168.1.1:88/test/test.txt”;
//下载文件保存位置
StringfilePath=”C:\\Users\\77025\\Desktop\\12345″;
URLurl=newURL(urlPath);
try{
downloadFile(url,filePath);
}catch(IOExceptione){
e.printStackTrace();
}
}
publicstaticvoiddownloadFile(URLtheURL,StringfilePath)throwsIOException{
FiledirFile=newFile(filePath);
//文件路径不存在时,自动创建目录
if(!dirFile.exists()){
dirFile.mkdir();
}
URLConnectionconnection=theURL.openConnection();
InputStreamin=connection.getInputStream();
//test.txt这里的text与下载文件名称最好一致
FileOutputStreamos=newFileOutputStream(filePath+”\\test.txt”);
byte[]buffer=newbyte[4*1024];
intread;
while((read=in.read(buffer))>0){
os.write(buffer,0,read);
}
os.close();
in.close();
}
}

未经允许不得转载:IT技术网站 » java下载文件到本地实现方法
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!

 

志在指尖 用双手敲打未来

登录/注册IT技术大全

热门IT技术

C#基础入门   SQL server数据库   系统SEO学习教程   WordPress小技巧   WordPress插件   脚本与源码下载