您的位置:首页 > 编程语言 > Java开发

Java操作,springMVC上传的文件

2016-07-11 00:00 513 查看
上篇文章写了如何用springMVC上传文件,现在记录一下如何操作上传的文件。

操作,无非是读取文件,写入磁盘上另一个文件中。(用的IO,NIO正在研究)。

InputStream fis =null;
FileOutputStream fos= null;
SimpleDateFormat format=new SimpleDateFormat("yyyyMMddHHmmss");


1、获取文件名:

//要上传的附件名,带后缀
String accessName = form.getTxtFile().getOriginalFilename();
//附件名截取,不带后缀
String shortAccessName=accessName.substring(0, accessName.lastIndexOf("."));


2、从properties配置文件中,获取保存文件路径。

InputStream in = this.getClass().getResourceAsStream("/param.properties");
Properties props = new Properties();
props.load(in);//  bookResourceMark.path=D-\\bookResourceMarkFile\\
//获取存放旧附件的文件夹路径,每一本图书单独建一个文件夹,这本书的历史附件都移到这个目录下 ,分pdf和epub
String dirPath = props.get("bookResourceMark.path").toString().replace("-",":")+shortAccessName+"\\"+form.getAccess().getType()+"\\";


3、原文件是否存在,如果存在,就加时间戳,然后将原文件另存为,再下载新文件。

//要上传的文件夹的路径
String path="这里面是文件保存路径";
//将改文件夹路径下的原附件移到别的文件夹中 ,加时间重命名
File oldFile=new File(path+"\\"+accessName);
if(oldFile.exists()){
//如果旧文件存在,则移动,移动前先判断要存放旧附件的文件夹是否存在,不存在就新建 ,存在直接移动
File fnewpath = new File(dirPath);
if(!fnewpath.exists()){
fnewpath.mkdirs();
}
String moveName= shortAccessName+"-"+format.format(new Date());
File newFile = new File(dirPath+ File.separator+(moveName+"."+form.getAccess().getType()));
oldFile.renameTo(newFile);
//移动完文件后,要修改该文件在附件表中的字段--》新旧状态、现在存放的地址、名称
condition.clear();
}


4、保存新文件。

//判断当前路径是否存在,如果路径不存在,创建路径。
File pathFile=new File(path);
if(!pathFile.exists()){
pathFile.mkdirs();
}


5、开始上传文件

上传文件

方法1、是制定固定长度的字节数组,每次取出固定的长度。

InputStream fis = form.getTxtFile().getInputStream();
FileOutputStream fos = new FileOutputStream(path + "\\" + accessName);
byte b[] = new byte[1024];
int read = fis.read(b);
while (read != -1) {
fos.write(b, 0, read);
read = fis.read(b);
}
fos.close();


方法2、CommonsMultipartFile中,CommonsMultipartFile.getFileItem().get(),直接获取所有数据的字节数组,

//form.getTxtFile().getFileItem().get()。
byte[] b = form.getTxtFile().getFileItem().get();
FileOutputStream fos = new FileOutputStream(path + "\\" + accessName);
fos.write(b);
fos.close();


这些就是操作(保存上传的文件,到另一个文件,或位置)文件的代码了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: