/**************************************************************************************工具类********************************************************************************************************/

package com.zero4j.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream; import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Component;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.MultipartFile; /**
*
* 上传工具类
*
*
*/
@Component
public class UploadUtil implements ServletContextAware { private static ServletContext servletContext = null; @Override
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
} /**
* 保存文件
*
* @param files
* @param id
* @param request
* @author hzr 2016年12月5日
*/
public static void fileSave(MultipartFile files, String id, HttpServletRequest request) {
String fileFileName = files.getOriginalFilename();
if (files == null || files.equals("")) {
return;
} else {
String extension = (fileFileName.substring(fileFileName.lastIndexOf(".") + 1, fileFileName.length())).toLowerCase(); // 获取扩展名并转换成小写
// 开始执行上传操作
try { // 设定图片上传的临时目录
File srcFile = new File(servletContext.getRealPath("/uploads/other/"), id + "." + extension);
System.out.println(srcFile);
if (!srcFile.exists()) {
System.out.println("路径不存在!!!!!!!!");
srcFile.mkdirs();
}
files.transferTo(srcFile); } catch (Exception e) {
e.printStackTrace();
return;
} /*
* //如果文件后缀不同则先删除原有文件
* if(files.getExtension()==null||!extension.equals
* (_upload.getExtension().toLowerCase())){ new
* File(ServletActionContext
* .getRequest().getRealPath("/uploads/other"),
* _upload.getId()+"."+_upload.getExtension()).deleteOnExit(); }
*
* //更新文件后缀到数据库中 _upload.setContentType(this.fileContentType);
* _upload.setExtension(extension);
* this.uploadService.update(_upload);
*/ // } } } /**
* 保存文件
*
* @param files
* @param id
* @param request
* @author hzr 2016年12月5日
*/
public static String fileSave_other(MultipartFile files, String id, HttpServletRequest request) {
String fileFileName = files.getOriginalFilename();
if (files == null || files.equals("")) {
return null;
} else {
String extension = (fileFileName.substring(fileFileName.lastIndexOf(".") + 1, fileFileName.length())).toLowerCase(); // 获取扩展名并转换成小写
// 开始执行上传操作
try { // 设定图片上传的临时目录 File srcFile = new File(servletContext.getRealPath("/uploads/styleItem/"), id + "." + extension);
System.out.println(srcFile);
if (!srcFile.exists()) {
System.out.println("文件路径不存在!!!!!!!!");
srcFile.mkdirs();
} /*String imageSourcePath = request.getRealPath("/uploads/styleItem");
File srcFile = new File(imageSourcePath, id + "." + extension);
if(!srcFile.exists()){
srcFile.mkdir();
}*/ //System.out.println(srcFile.toString()+"路径asdasdasdsa");
files.transferTo(srcFile);
return "/uploads/styleItem/"+id + "." + extension ;
} catch (Exception e) {
e.printStackTrace();
return null ;
} /*
* //如果文件后缀不同则先删除原有文件
* if(files.getExtension()==null||!extension.equals
* (_upload.getExtension().toLowerCase())){ new
* File(ServletActionContext
* .getRequest().getRealPath("/uploads/other"),
* _upload.getId()+"."+_upload.getExtension()).deleteOnExit(); }
*
* //更新文件后缀到数据库中 _upload.setContentType(this.fileContentType);
* _upload.setExtension(extension);
* this.uploadService.update(_upload);
*/ // } } } /**
* 删除文件夹
* @param filePathAndName String 文件夹路径及名称 如c:/fqf
* @param fileContent String
* @return boolean
*/
public static void delFolder(String folderPath) {
folderPath=servletContext.getRealPath(folderPath);
//System.out.println("执行删除文件夹操作 源文件路径"+folderPath);
try {
delAllFile(folderPath); //删除完里面所有内容
String filePath = folderPath;
filePath = filePath.toString();
java.io.File myFilePath = new java.io.File(filePath);
myFilePath.delete(); //删除空文件夹 }
catch (Exception e) {
System.out.println("删除文件夹操作出错");
e.printStackTrace(); } } /**
* 删除文件夹里面的所有文件
* @param path String 文件夹路径 如 c:/fqf
*/
public static void delAllFile(String path) {
path=servletContext.getRealPath(path); File file = new File(path);
if (!file.exists()) {
return;
}
if (!file.isDirectory()) {
return;
}
String[] tempList = file.list();
File temp = null;
for (int i = 0; i < tempList.length; i++) {
if (path.endsWith(File.separator)) {
temp = new File(path + tempList[i]);
}
else {
temp = new File(path + File.separator + tempList[i]);
}
if (temp.isFile()) { temp.delete();
}
if (temp.isDirectory()) {
delAllFile(path+"/"+ tempList[i]);//先删除文件夹里面的文件
delFolder(path+"/"+ tempList[i]);//再删除空文件夹
}
}
} /**
* 复制单个文件
* @param oldPath String 原文件相对路径 如:c:/fqf.txt
* @param newPath String 复制后相对路径 如:f:/fqf.txt
* @return boolean
*/
public static boolean copyFile(String oldPath, String newPath) {
// System.out.println("执行复制文件操作 源文件路径"+servletContext.getRealPath(oldPath)+" 目的文件路径 "+servletContext.getRealPath(newPath));
try {
// int bytesum = 0;
int byteread = 0;
File oldfile = new File(servletContext.getRealPath(oldPath)); File srcFile = new File(servletContext.getRealPath("/uploads/styleItemTemplate/"));
//System.out.println(srcFile);
if (!srcFile.exists()) {
System.out.println("文件夹路径不存在!!!!!!!!");
srcFile.mkdirs();
} File myFileName = new File(servletContext.getRealPath(newPath));
try{
if (!myFileName.exists()) {
myFileName.createNewFile();
}
}catch (Exception e) {
System.out.println("新建文件操作出错");
e.printStackTrace();
return false;
} if (oldfile.exists()) { //文件存在时
InputStream inStream = new FileInputStream(servletContext.getRealPath(oldPath)); //读入原文件
FileOutputStream fs = new FileOutputStream(servletContext.getRealPath(newPath)); byte[] buffer = new byte[1444];
// int length;
while ( (byteread = inStream.read(buffer)) != -1) {
// bytesum += byteread; //字节数 文件大小
// System.out.println(bytesum);
fs.write(buffer, 0, byteread); }
inStream.close(); fs.close();
// System.out.println("复制成功");
}
return true;
}
catch (Exception e) {
System.out.println("复制单个文件操作出错");
e.printStackTrace();
return false; } } /**
* 复制单个文件
* @param tempalteFileFolderRoute String 临时文件夹路径相对路径 如:c:/fqf
* @param newPath String 资源文件夹路径相对路径 如:f:/fqf1
* @return boolean
*/
public static boolean copyFileFolder(String tempalteFileFolderRoute, String newPath) {
// System.out.println("执行复制文件操作 源文件路径"+servletContext.getRealPath(oldPath)+" 目的文件路径 "+servletContext.getRealPath(newPath)); try {
File srcFile = new File(servletContext.getRealPath(tempalteFileFolderRoute));
if (!srcFile.exists()) {
System.out.println("文件夹路径不存在!!!!!!!!");
srcFile.mkdirs();
} File srcFile1 = new File(servletContext.getRealPath(newPath));
if (!srcFile1.exists()) {
System.out.println("文件夹路径不存在!!!!!!!!");
srcFile1.mkdirs();
} String path=servletContext.getRealPath(tempalteFileFolderRoute); File file = new File(path);
String[] tempList = file.list();
File temp = null;
for (int i = 0; i < tempList.length; i++) { String tempRoute=tempalteFileFolderRoute+"/"+tempList[i];
String normalRoute=newPath+"/"+tempList[i]; File oldfile = new File(servletContext.getRealPath(tempRoute)); File myFileName = new File(servletContext.getRealPath(normalRoute));
int byteread = 0;
try{
if (!myFileName.exists()) {
myFileName.createNewFile();
}
}catch (Exception e) {
System.out.println("新建文件操作出错");
e.printStackTrace();
return false;
} if (oldfile.exists()) { //文件存在时
InputStream inStream = new FileInputStream(servletContext.getRealPath(tempRoute)); //读入原文件
FileOutputStream fs = new FileOutputStream(servletContext.getRealPath(normalRoute)); byte[] buffer = new byte[1444];
// int length;
while ( (byteread = inStream.read(buffer)) != -1) {
// bytesum += byteread; //字节数 文件大小
// System.out.println(bytesum);
fs.write(buffer, 0, byteread); }
inStream.close();
//System.out.println("复制成功"); }
}
return true;
}
catch (Exception e) {
System.out.println("复制文件操作出错");
e.printStackTrace();
return false; }
} /*para
source 源文件目录
dest 复制文件目录
para*/
/*复制文件*/
public static void copyFile2(String source, String dest) {
System.out.println("执行复制文件操作 源文件路径"+servletContext.getRealPath(source)+" 目的文件路径 "+servletContext.getRealPath(dest)); File srcFile = new File(servletContext.getRealPath("/uploads/styleItemTemplate"));
System.out.println(srcFile);
if (!srcFile.exists()) {
System.out.println(servletContext.getRealPath(dest)+" 路径不存在!!!!!!!!");
srcFile.mkdirs();
} try {
File in = new File(servletContext.getRealPath(source));//源文件目录
File out = new File(servletContext.getRealPath(dest)); //复制文件目录
FileInputStream inFile = new FileInputStream(in);
FileOutputStream outFile = new FileOutputStream(out);
byte[] buffer = new byte[102400];
int i = 0;
while ((i = inFile.read(buffer)) != -1) {
outFile.write(buffer, 0, i);
}//end while
inFile.close();
outFile.close();
System.out.println("复制成功");
}//end try
catch (Exception e) {
System.out.println(e.toString());
}//end catch
}//end copyFile /*删除文件方法*/
public boolean deleteFile(String sPath) {
System.out.println("执行删除文件操作 源文件路径"+servletContext.getRealPath("/uploads/styleItem")+sPath); boolean flag = false;
File file = new File(servletContext.getRealPath("/uploads/styleItem")+sPath);
// 路径为文件且不为空则进行删除
if (file.isFile() && file.exists()) {
file.delete();
flag = true;
}
return flag;
} } /************************************************************************调用*****************************************************************************/ @RequestParam MultipartFile[] imgRoute uuid-->file name UploadUtil.fileSave_other(uploadFiles[k], uuid,
request); /*************************************************************************************前端 代码**************************************************************************************/     /**********************************************************jsp**************************************************************/ <input type="file" name="imgRoute" class="fileRouteIn" value=""
style="width:200px; display:inline;" required="required" />   /******************************************************************************js*************************************************************************/ /* 发送上传文件请求
para--uploadFiles 选择文件 fileRouteIn--name
para--num 选择文件 fileRouteIn--index序号
*/
function uploadFile(uploadFiles, num) {
// alert(num);
$(".fileRouteIn:eq(" + num + ")").text(
$(".fileRouteIn:eq(" + num + ")").val());
var token = $.cookie("token");
$.ajaxFileUpload({
url : "api/v1/styleItems/uploadFile?token=" + token,
type : "POST",
secureuri : false,
fileElementId : uploadFiles,//该参数名要与input【type=‘file’】 的name相同
dataType : "json",
success : function(response) {
if (response.status == 200) {
blackDialog.show(response.uploadFileRoute);
var valueaa = response.uploadFileRoute; $(".fileRouteIn:eq(" + num + ")").attr("value",
response.uploadFileRoute);
$(".viewMessege:eq(" + num + ")").text("所选文件上传成功");
console.log(valueaa + "213123");
blackDialog.show(response.message); $(".processbar:eq(" + num + ")").width("95%"); } else {
window.clearInterval(bartimer);
$(".processbar:eq(" + num + ")").width("0%");
$(".processbar:eq(" + num + ")").text(0 + "%");
$(".viewMessege:eq(" + num + ")").text("文件上传失败");
blackDialog.show(response.message); } }
}); }

java File处理的更多相关文章

  1. Java File类总结和FileUtils类

    Java File类总结和FileUtils类 文件存在和类型判断 创建出File类的对象并不代表该路径下有此文件或目录. 用public boolean exists()可以判断文件是否存在. Fi ...

  2. Java File 类的使用方法详解

    Java File类的功能非常强大,利用Java基本上可以对文件进行所有的操作.本文将对Java File文件操作类进行详细地分析,并将File类中的常用方法进行简单介绍,有需要的Java开发者可以看 ...

  3. Java File 类的使用方法详解(转)

    转自:http://www.codeceo.com/article/java-file-class.html Java File类的功能非常强大,利用Java基本上可以对文件进行所有的操作.本文将对J ...

  4. Java——File类成员方法

    body, table{font-family: 微软雅黑} table{border-collapse: collapse; border: solid gray; border-width: 2p ...

  5. An error occurred at line: 1 in the generated java file问题处理

    tomcat6启动后,加载jsp页面报错,提示无法将jsp编译为class文件,主要报错信息如下: An error occurred at line: 1 in the generated java ...

  6. 报错:An error occurred at line: 22 in the generated java file The method getJspApplicationContext(ServletContext) is undefined for the type JspFactory

    org.apache.jasper.JasperException: Unable to compile class for JSP: An error occurred at line: 22 in ...

  7. Java File类 mkdir 不能创建多层目录

    File f = new File("/home/jp/Upload"); if ((!f.exists()) || (!f.isDirectory())) {boolean re ...

  8. Java File类方法使用详解

    Java File类的功能非常强大,利用java基本上可以对文件进行所有操作.文本将对Java File 文件操作的类详细的分析,并将File类中的常用方法进行简单介绍. 构造函数 public cl ...

  9. 【转载】Java File操作汇总

    转载自博客:https://passport.cnblogs.com/user/signin?ReturnUrl=https%3A%2F%2Fwww.cnblogs.com%2F 本文通过大量的示例, ...

  10. JAVA File的创建及相对路径绝对路径

    http://blog.sina.com.cn/s/blog_9386f17b0100w2vv.html JAVA File的创建及相对路径绝对路径 (2011-12-09 08:27:56) 转载▼ ...

随机推荐

  1. HTML中引用外部JS文件失效原因

    今天在练习中碰到“引用外部的一个js文件但是却失效”的情况,实在不懂,百度后才知是引用的位置不对,错误的代码如下: <head> <meta charset="UTF-8& ...

  2. [luogu P2234] [HNOI2002]营业额统计

    [luogu P2234] [HNOI2002]营业额统计 题目描述 Tiger最近被公司升任为营业部经理,他上任后接受公司交给的第一项任务便是统计并分析公司成立以来的营业情况. Tiger拿出了公司 ...

  3. koa和express对比

    不同: 1.启动方式不同 koa采用了new Koa()的方式,而express采用传统的函数形式 2.中间件形式二者不一样,这是由二者处理中间件的逻辑差异导致的,实际上这也是二者最根本的差别 3.k ...

  4. leetcode python 010

    #实现正则表达式匹配并支持'.'和'*'.#''匹配任何单个字符.#'*'匹配前面元素的零个或多个.#匹配应覆盖整个输入字符串(非部分).##Some examples:##isMatch(" ...

  5. redis列表操作基本命令

    RPUSH:从列表尾部插入一个元素,RPOP:返回列表最后一个元素并从列表删除LPUSH:从列表头部插入一个元素,LPOP:返回列表第一个元素并从列表删除(没看到命名的介绍,个人理解R就是right, ...

  6. msfvenom生成各类Payload命令

    Often one of the most useful (and to the beginner underrated) abilities of Metasploit is the msfpayl ...

  7. 北大poj- 1032

    Parliament Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 18707   Accepted: 7941 Descr ...

  8. 2019-04-17-day034-线程与数据共享

    内容回顾 锁 互斥锁 能够保护数据的安全性 保证对于数据的修改操作同一时刻多个进程只有一个进程执行 进程数据不安全 : 同时修改文件/数据库/其他共享资源的数据 ###队列 -- 实现了进程之间的通信 ...

  9. 剑指Offer 4. 重建二叉树 (二叉树)

    题目描述 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树.假设输入的前序遍历和中序遍历的结果中都不含重复的数字.例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7, ...

  10. 如何在 Windows 中设置 /3GB 启动开关

    备注: 只有在下列操作系统中才支持 /3GB 开关: Windows 2000 Advanced Server Windows 2000 Datacenter Server Windows Serve ...