java实现文件保存到本地的方法
本篇介绍了java实现文件保存到本地的方法,具体代码如下:
privatevoidsavePic(InputStreaminputStream,StringfileName){
OutputStreamos=null;
try{
Stringpath="D:\\testFile\\";
//2、保存到临时文件
//1K的数据缓冲
byte[]bs=newbyte[1024];
//读取到的数据长度
intlen;
//输出的文件流保存到本地文件
FiletempFile=newFile(path);
if(!tempFile.exists()){
tempFile.mkdirs();
}
os=newFileOutputStream(tempFile.getPath()+File.separator+fileName);
//开始读取
while((len=inputStream.read(bs))!=-1){
os.write(bs,0,len);
}
}catch(IOExceptione){
e.printStackTrace();
}catch(Exceptione){
e.printStackTrace();
}finally{
//完毕,关闭所有链接
try{
os.close();
inputStream.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
文件保存方法.
附:
packagecom.ebways.web.upload.controller;
importjava.io.*;
importjava.text.SimpleDateFormat;
importjava.util.Date;
importjava.util.HashMap;
importjava.util.Map;
importcom.ebways.web.base.BaseController;
importorg.springframework.stereotype.Controller;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RequestParam;
importorg.springframework.web.bind.annotation.ResponseBody;
importcom.ebways.web.upload.url.UploadURL;
importorg.springframework.web.multipart.MultipartFile;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
@Controller
@RequestMapping(value=UploadURL.MODE_NAME)
publicclassUploadControllerextendsBaseController{
@RequestMapping(value=UploadURL.IMAGE_UPLOAD)
@ResponseBody
publicStringuploadFile(MultipartFilefile,HttpServletRequestrequest,HttpServletResponseresponse)throwsIllegalArgumentException,Exception{
//参数列表
Map<String,Object>map=newHashMap<>();
map.put("file",file);
savePic(file.getInputStream(),file.getOriginalFilename());
//请求接口
StringapiReturnStr="";//apiHttpRequest(map,API_HOST_URL+"/image/upload");
returnapiReturnStr;
}
privatevoidsavePic(InputStreaminputStream,StringfileName){
OutputStreamos=null;
try{
Stringpath="D:\\testFile\\";
//2、保存到临时文件
//1K的数据缓冲
byte[]bs=newbyte[1024];
//读取到的数据长度
intlen;
//输出的文件流保存到本地文件
FiletempFile=newFile(path);
if(!tempFile.exists()){
tempFile.mkdirs();
}
os=newFileOutputStream(tempFile.getPath()+File.separator+fileName);
//开始读取
while((len=inputStream.read(bs))!=-1){
os.write(bs,0,len);
}
}catch(IOExceptione){
e.printStackTrace();
}catch(Exceptione){
e.printStackTrace();
}finally{
//完毕,关闭所有链接
try{
os.close();
inputStream.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
/**
*<pclass="detail">
*功能:公共Action
*</p>
*
*@date2016年9月8日
*@authorwangsheng
*/
privateStringallowSuffix="jpg,png,gif,jpeg";//允许文件格式
privatelongallowSize=2L;//允许文件大小
privateStringfileName;
privateString[]fileNames;
publicStringgetAllowSuffix(){
returnallowSuffix;
}
publicvoidsetAllowSuffix(StringallowSuffix){
this.allowSuffix=allowSuffix;
}
publiclonggetAllowSize(){
returnallowSize*1024*1024;
}
publicvoidsetAllowSize(longallowSize){
this.allowSize=allowSize;
}
publicStringgetFileName(){
returnfileName;
}
publicvoidsetFileName(StringfileName){
this.fileName=fileName;
}
publicString[]getFileNames(){
returnfileNames;
}
publicvoidsetFileNames(String[]fileNames){
this.fileNames=fileNames;
}
/**
*<pclass="detail">
*功能:重新命名文件
*</p>
*
*@return
*@authorwangsheng
*@date2016年9月8日
*/
privateStringgetFileNameNew(){
SimpleDateFormatfmt=newSimpleDateFormat("yyyyMMddHHmmssSSS");
returnfmt.format(newDate());
}
/**
*<pclass="detail">
*功能:文件上传
*</p>
*
*@paramfiles
*@paramdestDir
*@throwsException
*@authorwangsheng
*@date2014年9月25日
*/
publicvoiduploads(MultipartFile[]files,StringdestDir,HttpServletRequestrequest)throwsException{
Stringpath=request.getContextPath();
StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
try{
fileNames=newString[files.length];
intindex=0;
for(MultipartFilefile:files){
Stringsuffix=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
intlength=getAllowSuffix().indexOf(suffix);
if(length==-1){
thrownewException("请上传允许格式的文件");
}
if(file.getSize()>getAllowSize()){
thrownewException("您上传的文件大小已经超出范围");
}
StringrealPath=request.getSession().getServletContext().getRealPath("/");
FiledestFile=newFile(realPath+destDir);
if(!destFile.exists()){
destFile.mkdirs();
}
StringfileNameNew=getFileNameNew()+"."+suffix;//
Filef=newFile(destFile.getAbsoluteFile()+"\\"+fileNameNew);
file.transferTo(f);
f.createNewFile();
fileNames[index++]=basePath+destDir+fileNameNew;
}
}catch(Exceptione){
throwe;
}
}
/**
*功能:文件上传
*
*@paramfile
*@paramdestDir
*@throwsException
*@authorwangsheng
*@date2016年9月8日
*/
publicvoidupload(MultipartFilefile,StringdestDir,HttpServletRequestrequest)throwsException{
Stringpath=request.getContextPath();
StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
try{
Stringsuffix=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
intlength=getAllowSuffix().indexOf(suffix);
if(length==-1){
thrownewException("请上传允许格式的文件");
}
if(file.getSize()>getAllowSize()){
thrownewException("您上传的文件大小已经超出范围");
}
StringrealPath=request.getSession().getServletContext().getRealPath("/");
FiledestFile=newFile(realPath+destDir);
if(!destFile.exists()){
destFile.mkdirs();
}
StringfileNameNew=getFileNameNew()+"."+suffix;
Filef=newFile(destFile.getAbsoluteFile()+"/"+fileNameNew);
file.transferTo(f);
f.createNewFile();
fileName=basePath+destDir+fileNameNew;
}catch(Exceptione){
throwe;
}
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。