java实现服务器下载到本地

来源:互联网 发布:java log4j2.xml 编辑:程序博客网 时间:2024/06/03 13:28

从服务器下载文件到本地,并以当天日期命名文件夹,文件以改信息的id命名。

以流的形式下载文件  (FileInputStream、FileOutputStream 文件输入输出流)。

直接上代码展示:

public String getCmsInfoListener() throws IOException{

SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式 
Date todaydate = new Date();  
Calendar c = Calendar.getInstance();  
        c.setTime(todaydate);  
        c.add(Calendar.DAY_OF_MONTH, 1);// 今天+1天  
   
        Date tomorrowdate = c.getTime();  
String today = f.format(todaydate);//今天
String tomorrow =  f.format(tomorrowdate);//明天 

//String filePath = PageParameterInit.getFilePath();// 得到外网文件路径
String exportFilePath = PageParameterInit.getExportFilePath();// 得到导出文件路径
//根据时间段获取数据集合
List<CmsInfo> list = cmsInfoDao.getCmsInfoByOptime(today, tomorrow);
CmsInfo cmsInfo;
String fileUrl;//文件url
for (int i = 0; i < list.size(); i++) {
cmsInfo = list.get(i);
fileUrl = cmsInfo.getFileUrl();
InputStream fis = null;
try {
//获取文件路径,并判断文件是否存在
File file = new File(fileUrl);
if (!file.exists()) {
return null;
}
String newUrl = exportFilePath+today;//目标文件路径
String oldUrl =fileUrl;//源文件路径
//把源文件名称修改为id
String name = "\\"+cmsInfo.getId() +"." +fileUrl.substring(fileUrl.lastIndexOf(".")+1);
doDownload(oldUrl, newUrl,name);
} catch (IOException e) {
System.out.println("异常信息:"+e.toString());
throw  new IOException();
} finally {
if (null != fis) {
try {
fis.close();
} catch (IOException e) {
System.out.println("异常信息:"+e.toString());
}
}
}
}
return null;
}

private void doDownload(String oldUrl,String newUrl,String filename) throws IOException {
try {
int bytesum = 0;
int byteread = 0;
//原文件
File oldfile = new File(oldUrl);
//目标文件
File file = new File(newUrl);
//判断目标文件夹是否存在,不存在时新建文件夹
if (!file.exists()) {
file.mkdirs();
}
if (oldfile.exists()) { // 文件存在时
InputStream inStream = new FileInputStream(oldUrl); // 读入原文件
FileOutputStream fs = new FileOutputStream(newUrl+filename);
byte[] buffer = new byte[1444];
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; // 字节数 文件大小
fs.write(buffer, 0, byteread);

}

//关闭流

inStream.close();
}
} catch (Exception e) {
System.out.println("复制单个文件操作出错"+e.toString());
}
       System.out.println("写入成功!");
}
}
阅读全文
0 0
原创粉丝点击