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

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. 『PyTorch × TensorFlow』第十七弹_ResNet快速实现

    『TensorFlow』读书笔记_ResNet_V2 对比之前的复杂版本,这次的torch实现其实简单了不少,不过这和上面的代码实现逻辑过于复杂也有关系. 一.PyTorch实现 # Author : ...

  2. 万年不变话题cookie,简单总结

    cookie是面试中经常会问到的一个问题,但是就我的项目实践来看,我用到的次数极少.有时候用到也不是为了存储用户名密码,只是存储一些需要记住的状态.可能和我的经验尚浅,涉足的项目不算多有关.这里简单做 ...

  3. js 把一个对象赋值给另一个对象会指向同一个内存地址

    先看一段代码: var arr1 = [1,2,3]; var arr2 = arr1; arr2.push(4); console.log(arr1)//[1,2,3,4] 为什么会输出 的是[1, ...

  4. 使用Metasploit渗透攻击windows系统(二)

    后渗透攻击: 介绍常用的一些命令: 查看进程:ps 查看当前进程号:getpid 查看系统信息:sysinfo 查看目标机是否为虚拟机:run post/windows/gather/checkvm ...

  5. tcp滑动窗口详解(2)

    http://blog.csdn.net/yujun00/article/details/636495 ARQ与滑动窗口概念  滑动窗口协议,是TCP使用的一种流量控制方法.该协议允许发送方在停止并等 ...

  6. MySQL造数据脚本-亲试

    DELIMITER $$CREATE DEFINER=`root`@`192.168.2.254` PROCEDURE `pjzzspdz_fpmx_initdata12101245`()BEGIN ...

  7. c# 转换成时间类型

    if (rngFound.Value.ToString().Contains("/")) { closingdate = rngFound.Value; } else if (rn ...

  8. zk observer 节点

    zk 集群中有3种节点:leader,follower,observer,其中 observer 节点没有投票权,即它不参与选举和写请求的投票. 比较 Follower 和 Observer 的代码: ...

  9. CodeForces - 1015 D.Walking Between Houses

    Description Natasha is planning an expedition to Mars for nn people. One of the important tasks is t ...

  10. python基础——元组

    元组运算符 与字符串一样,元组之间可以使用 + 号和 * 号进行运算.这就意味着他们可以组合和复制,运算后会生成一个新的元组. Python 表达式 结果 描述 len((1, 2, 3)) 3 计算 ...