FileUtils删除文件的工具类

时间:2023-03-09 22:31:41
FileUtils删除文件的工具类

  

  前提是知道文件在哪个文件夹下面然后到文件夹下面删除文件,如果文件夹也需要传参数需要对下面方法进行改造。

   ( 需要借助于commons-io.jar和ResourceUtils.java  )

  

1.DeleteFileUtil.java工具类

package com.tyust.common;

import java.io.File;
import java.io.IOException; import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils; /**
* 根据文件的名字到对应的文件夹下面删除对应的文件
*
* @author QiaoLiQiang
* @time 2018年2月6日下午2:22:40
*/
public class DeleteFileUtil {
/**
* 删除文件(因为一个文件可能存在pdf,doc,docx三种格式,因此需要删除)
*
* @param fileName
* @return
*/
public static boolean deleteFile(String fileName) {
if (fileName == null) {
return false;
}
String dir = ResourcesUtil.getValue("path", "file");// 获取文件的基本目录
String baseName = FilenameUtils.getBaseName(fileName);// 获取文件的基本名字
try {
FileUtils.forceDeleteOnExit(new File(dir + baseName + ".pdf"));
FileUtils.forceDeleteOnExit(new File(dir + baseName + ".doc"));
FileUtils.forceDeleteOnExit(new File(dir + baseName + ".docx"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
} /**
* 到存放图片的文件夹下面删除图片
*
* @param fileName
* @return
*/
public static boolean deletePicture(String fileName) {
if (fileName == null) {
return false;
}
String dir = ResourcesUtil.getValue("path", "picture");// 获取文件图片的基本目录
try {
FileUtils.forceDeleteOnExit(new File(dir + fileName));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
} public static void main(String[] args) {
DeleteFileUtil.deleteFile("ef0c4d250561413e9777fb439e8fbc27.doc");
System.out.println("sss");
}
}

  解释:

ResourcesUtil是读取配置文件中的目录路径,FilenameUtils(位于commons-io.jar)是获取传来的文件的基本名字,文件夹下面根据基本名字删除pdf、doc、docx文件。
ResourcesUtil.java 读取.properties文件中的目录路径
package com.tyust.common;

import java.io.Serializable;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.Set; /**
* 读取properties文件的工具类
* @author QiaoLiQiang
* @time 2018年2月5日下午4:28:18
*/
public class ResourcesUtil implements Serializable { private static final long serialVersionUID = -7657898714983901418L; /**
* 系统语言环境,默认为中文zh
*/
public static final String LANGUAGE = "zh"; /**
* 系统国家环境,默认为中国CN
*/
public static final String COUNTRY = "CN";
private static Locale getLocale() {
Locale locale = new Locale(LANGUAGE, COUNTRY);
return locale;
} /**
* 根据语言、国家、资源文件名和key名字获取资源文件值
*
* @param language
* 语言
*
* @param country
* 国家
*
* @param baseName
* 资源文件名
*
* @param section
* key名字
*
* @return 值
*/
private static String getProperties(String baseName, String section) {
String retValue = "";
try {
Locale locale = getLocale();
ResourceBundle rb = ResourceBundle.getBundle(baseName, locale);
retValue = (String) rb.getObject(section);
} catch (Exception e) {
e.printStackTrace();
// TODO 添加处理
}
return retValue;
} /**
* 通过key从资源文件读取内容
*
* @param fileName
* 资源文件名
*
* @param key
* 索引
*
* @return 索引对应的内容
*/
public static String getValue(String fileName, String key) {
String value = getProperties(fileName,key);
return value;
} public static List<String> gekeyList(String baseName) {
Locale locale = getLocale();
ResourceBundle rb = ResourceBundle.getBundle(baseName, locale); List<String> reslist = new ArrayList<String>(); Set<String> keyset = rb.keySet();
for (Iterator<String> it = keyset.iterator(); it.hasNext();) {
String lkey = (String)it.next();
reslist.add(lkey);
} return reslist; } /**
* 通过key从资源文件读取内容,并格式化
*
* @param fileName
* 资源文件名
*
* @param key
* 索引
*
* @param objs
* 格式化参数
*
* @return 格式化后的内容
*/
public static String getValue(String fileName, String key, Object[] objs) {
String pattern = getValue(fileName, key);
String value = MessageFormat.format(pattern, objs);
return value;
} public static void main(String[] args) {
System.out.println(getValue("resources.messages", "101",new Object[]{100,200})); //根据操作系统环境获取语言环境
/*Locale locale = Locale.getDefault();
System.out.println(locale.getCountry());//输出国家代码
System.out.println(locale.getLanguage());//输出语言代码s //加载国际化资源(classpath下resources目录下的messages.properties,如果是中文环境会优先找messages_zh_CN.properties)
ResourceBundle rb = ResourceBundle.getBundle("resources.messages", locale);
String retValue = rb.getString("101");//101是messages.properties文件中的key
System.out.println(retValue); //信息格式化,如果资源中有{}的参数则需要使用MessageFormat格式化,Object[]为传递的参数,数量根据资源文件中的{}个数决定
String value = MessageFormat.format(retValue, new Object[]{100,200});
System.out.println(value);
*/ }
}

path.properties

#the directory of environment file to save
file=F:/sbgl/file/
picture=F:/sbgl/picture/

最后附一个自己封装的删除文件的完整的工具类:

package cn.xm.jwxt.utils;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile; import java.io.*;
import java.util.Locale;
import java.util.ResourceBundle; /**
* @Author: qlq
* @Description 文件处理类
* @Date: 22:59 2018/4/9
*/
public class FileHandleUtil {
/******S 封装的读取properties文件****************/
/**
* 系统语言环境,默认为中文zh
*/
public static final String LANGUAGE = "zh"; /**
* 系统国家环境,默认为中国CN
*/
public static final String COUNTRY = "CN"; private static String getProperties(String baseName, String section) {
String retValue = "";
try {
Locale locale = new Locale(LANGUAGE, COUNTRY);
ResourceBundle rb = ResourceBundle.getBundle(baseName, locale);
retValue = (String) rb.getObject(section);
} catch (Exception e) {
e.printStackTrace();
// TODO 添加处理
}
return retValue;
}
/**
* 通过key从资源文件读取内容
*
* @param fileName
* 资源文件名
*
* @param key
* 索引
*
* @return 索引对应的内容
*/
public static String getValue(String fileName, String key) {
String value = getProperties(fileName,key);
return value;
}
/******E 封装的读取properties文件****************/ /**********S 保存文件相关操作**************/
/**
* 配置虚拟路径上传文件到本地磁盘
* @param f 需要上传的文件
* @param fileName 保存到磁盘的文件名
* @param pathKey 资源文件中的键 path.properties
*/
public static void uploadFileToDisk(File f,String fileName,String pathKey){
//从资源文件中读取文件的基本目录
String basePath = ResourcesUtil.getValue("path", pathKey);
//获取文件的后缀
String sufix = FilenameUtils.getExtension(fileName);
//获取文件的前缀
String prefix = FilenameUtils.getBaseName(fileName);
//保存到硬盘的文件的完整路径
String dir = basePath+fileName;
try{
InputStream streamIn = new FileInputStream(f);
OutputStream streamOut = new FileOutputStream(new File(dir));
int bytesRead=0;
byte[] byffer = new byte[8192];
while((bytesRead=streamIn.read(byffer,0,8192))!=-1){
streamOut.write(byffer, 0, bytesRead);
}
streamIn.close();
streamOut.flush();
streamOut.close();
} catch (IOException e) {
e.printStackTrace();
}
//如果文件是doc或者docx文件将文件转为pdf存一份到服务器
if("doc".equals(sufix)||"docx".equals(sufix)){
try {
// Word2PdfUtil.word2pdf(dir, basePath+prefix+".pdf");
} catch (Exception e) {
e.printStackTrace();
}
}
} /**********E 保存文件相关操作**************/ /******************S 删除文件相关操作********/
/**
*删除word(有可能后缀是doc,docx,或者转换后的pdf文件)
* @param propertiesKey path.properties文件中的key(确定目录)
* @param fileName 需要删除的文件的名字(确定删除哪个文件)
* @return 删除结果
*/
public static boolean deleteWordOrPdfFile(String propertiesKey,String fileName) {
if (fileName == null) {
return false;
}
String dir = FileHandleUtil.getValue("path", propertiesKey);// 获取文件的基本目录
String baseName = FilenameUtils.getBaseName(fileName);// 获取文件的基本名字(借助commons-io包读取文件基本名称)
try {
FileUtils.deleteQuietly(new File(dir + baseName + ".pdf"));
FileUtils.deleteQuietly(new File(dir + baseName + ".doc"));
FileUtils.deleteQuietly(new File(dir + baseName + ".docx"));
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
/**
*删除普通的文件(jpg,word,pdf)
* @param propertiesFileName properties文件的名称(确定读取哪个properties文件)
* @param propertiesKey properties文件中的key(确定目录)
* @param fileName 需要删除的文件的名字(确定删除哪个文件)
* @return 删除结果
*/
public static boolean deletePlainFile(String propertiesFileName,String propertiesKey,String fileName) {
if (fileName == null) {
return false;
}
String dir = FileHandleUtil.getValue(propertiesFileName, propertiesKey);// 获取文件的基本目录
try {
//删除文件
// FileUtils.forceDeleteOnExit(new File(dir + fileName));
FileUtils.deleteQuietly(new File(dir + fileName));
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
/****************E 删除文件相关操作**************/ /******* S针对SptingMVC的上传文件的处理 *************/
/**
* 专门针对SpringMVC的文件上传操作
* @param multipartFile 文件参数
* @param propertiesKey 需要读取的path里面的key
* @param fileName 文件名字,比如: ce5bd946fd43410c8a26a6fa1e9bf23c.pdf
* @return 返回值是最后的文件名字,如果是word需要转成pdf,1.doc返回值就是1.pdf
*/
public static String uploadSpringMVCFile(MultipartFile multipartFile,String propertiesKey,String fileName) throws Exception {
String fileDir = FileHandleUtil.getValue("path", propertiesKey);// 获取文件的基本目录
//1.将文件保存到指定路径
multipartFile.transferTo(new File(fileDir+fileName));//保存文件
//2.根据文件后缀判断文件是word还是pdf,如果是word需要转成pdf,其他的话不做处理
String fileNameSuffix = FilenameUtils.getExtension(fileName);//调用io包的工具类获取后缀
if("doc".equals(fileNameSuffix)||"docx".equals(fileNameSuffix)){//如果后缀是doc或者docx的话转为pdf另存一份
String fileNamePrefix = FilenameUtils.getBaseName(fileName);//获取文件前缀名字
Word2PdfUtil.word2pdf(fileDir+fileName,fileDir+fileNamePrefix+".pdf");//进行word转换pdf操作
fileName = fileNamePrefix+".pdf";//并将文件的名字换成新的pdf名字
}
return fileName;
}
/******* E针对SptingMVC的上传文件的处理 *************/ }

保存word的时候依赖于word转pdf:

package cn.xm.jwxt.utils;

import java.io.File;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
/**
* word转pdf工具类
* @author QiaoLiQiang
* @time 2018年1月5日下午7:16:12
*/
public class Word2PdfUtil {
static final int wdFormatPDF = 17;// PDF 格式
public static void main(String[] args) throws Exception {
String source1 = "C:\\Users\\liqiang\\Desktop\\sbgl.docx";
String target1 = "C:\\Users\\liqiang\\Desktop\\sbgl.pdf";
Word2PdfUtil.word2pdf(source1, target1);
} /**
* 实现转换word文档为PDF文档
* @param docFileName doc文件全路径(路径+文件名)
* @param toFileName PDF文件全路径(路径+文件名)
* @throws Exception
*/
public static boolean word2pdf(String docFileName,String toFileName) throws Exception {
ComThread.InitSTA();
System.out.println("启动Word..."); long start = System.currentTimeMillis();
ActiveXComponent app = null;
Dispatch doc = null; try {
app = new ActiveXComponent("Word.Application");
app.setProperty("Visible", new Variant(false));
Dispatch docs = app.getProperty("Documents").toDispatch();
doc = Dispatch.call(docs, "Open" , docFileName).toDispatch(); System.out.println("打开文档..." + docFileName);
System.out.println("转换文档到PDF..." + toFileName); File tofile = new File(toFileName);
if (tofile.exists()) {
tofile.delete();
} Dispatch.call(doc,
"SaveAs",
toFileName,
wdFormatPDF); long end = System.currentTimeMillis();
System.out.println("转换完成..用时:" + (end - start) + "ms."); } catch (Exception e) {
System.out.println("========Error:文档转换失败:" + e.getMessage());
return false;
} finally {
try {
Dispatch.call(doc,"Close",false);
System.out.println("关闭文档");
if (app != null) {
app.invoke("Quit", 0);
} ComThread.Release();
} catch(Exception ex) { }
}
return true;
}
}