在开发中经常会用到文件操作类,这里封装一下,以便大家参考
/**
*
* 附件类型参数
*
*/
public class ParseType {
/*
* 附件类型
*/
public static long PNG = 13; //png
public static long ZIP = 12; //zip
public static long RAR = 11; //rar
public static long HTML = 10; //html
public static long PPT = 9; //ppt,pptx
public static long AUDIO = 8;
public static long WORD = 7; //doc,docx,rtf
public static long TXT = 6;
public static long EXCEL = 5;//xls,xlsx
public static long PDF = 4;
public static long JPG = 3;
public static long GIF = 2;
public static long BMP = 1;
public static long OTHER = 0;
}
/**
*
* 文件操作工具类
*
*/
public class FileUtil {
private static int BUFFER = 5096;
//合法的图片文件后缀
public static final String validImagSuffix = ".gif|.jpg|.png|.bmp";
public static boolean isValidImagSuffix(String suffix){
boolean flg = false;
String [] s = validImagSuffix.split("\\|");
for(String str:s){
if(suffix.equals(str)){
flg = true;
break;
}
}
return flg;
}
/**
* get file suffix according to the filename
*
* @param fileName
* @return
* @throws BizException
*/
public static String getFileSuffix(String fileName)
throws BizException {
int sufIndex = fileName.lastIndexOf(".");
if (sufIndex < 0)
throw new BizException("");
String suffix = fileName.substring(sufIndex);
return suffix;
}
public static String getFileName(String fileName) throws BizException {
int start = fileName.lastIndexOf("\\");
int sufIndex = fileName.lastIndexOf(".");
if (sufIndex < 0)
throw new BizException("");
String suffix = fileName.substring(start + 1, sufIndex);
return suffix;
}
/**复制文件
* @param source
* @param desc
* @return
*/
public static boolean copyFile(String source, String desc) {
FileInputStream is = null;
FileOutputStream os = null;
try {
File fl = new File(source);
int length = (int) fl.length();
is = new FileInputStream(source);
os = new FileOutputStream(desc);
byte[] b = new byte[length];
is.read(b);
os.write(b);
return true;
}
catch (Exception e) {
throw new BizException(e.getMessage());
}
finally{
try {
os.flush();
is.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 创建文件夹
* @param dirFile
* @return boolean
*/
public static boolean createDir(File dirFile){
boolean creadok = false;
if (!(dirFile.exists()) && !(dirFile.isDirectory())) {
creadok = dirFile.mkdirs();
}
return creadok;
}
/**
* 删除文件夹
* @param sPath
* @return boolean
*/
public static boolean deleteFile(String sPath) {
boolean flag = false;
File file = new File(sPath);
// 路径为文件且不为空则进行删除
if (file.isFile() && file.exists()) {
file.delete();
File parent = file.getParentFile();
if(parent.isDirectory() && parent.listFiles().length<=0){
parent.delete();
File temp = parent.getParentFile();
deleteFile(temp.getAbsolutePath());
}
flag = true;
}else{
File parent = new File(sPath);
if(parent.isDirectory() && parent.listFiles().length<=0){
parent.delete();
File temp = parent.getParentFile();
deleteFile(temp.getAbsolutePath());
flag = true;
}
}
return flag;
}
/**
* 验证图片文件
* @param suffix
* @return
*/
public static String filternoValiddSuffixImg(String suffix){
if(".png".equals(suffix)){
return null;
}else if(".bmp".equals(suffix)){
return null;
}else if(".jpg".equals(suffix)){
return null;
}else if(".gif".equals(suffix)){
return null;
}
return "error";
}
/**
* 根据文件后缀确定对应的ParseType
* @param suffix 文件在网页中的后缀
* @param realSuffix 文件的真实后缀
* @param fileType 文件对应ParseType的类型
*/
public static String confirmFileSuffix(String suffix){
String fileInfo = "";
String realSuffix = "";
long fileType = 0l ;
//判断
if(suffix.equals(".pdf")) {// 4
realSuffix =".pdf";
fileType = ParseType.PDF;
}else if (suffix.equals(".jpg") || suffix.equals(".jpeg") || suffix.equals("[image/jpeg]") || suffix.equals("[image/jpg]")) {// 3
realSuffix =".jpg";
fileType = ParseType.JPG;
}else if (suffix.equals(".bmp")) {// 1
realSuffix =".bmp";
fileType = ParseType.BMP;
}else if (suffix.equals(".gif") || suffix.equals("[image/gif]") ) {// 2
realSuffix =".gif";
fileType = ParseType.GIF;
}else if (suffix.equals(".png") || suffix.equals("[image/png]")){
realSuffix =".png";
fileType = ParseType.PNG; //image/png
}else if (suffix.equals(".doc") || suffix.equals(".docx")) {// 7
realSuffix =".doc";
fileType = ParseType.WORD;
}else if (suffix.equals(".xls") || suffix.equals(".xlsx")) {// 5
realSuffix =".xls";
fileType = ParseType.EXCEL;
}else if (suffix.equals(".ppt") || suffix.equals(".pptx")) {// 9
realSuffix =".ppt";
fileType = ParseType.PPT;
}else if (suffix.equals(".html") || suffix.equals(".htm") || suffix.equals(".mht")) {// 10
realSuffix =".htm";
fileType = ParseType.HTML;
}else if (suffix.equals(".txt")) {// 6
realSuffix =".txt";
fileType = ParseType.TXT;
}else if (suffix.equals(".rar")) {// 6
realSuffix =".rar";
fileType = ParseType.RAR;
}else if (suffix.equals(".zip")) {// 6
realSuffix =".zip";
fileType = ParseType.ZIP;
}
fileInfo = realSuffix + "$" + String.valueOf(fileType);
return fileInfo;
}
public static boolean isFileExist(String fileUrl){
File file = new File(fileUrl);
return file.exists();
}
private static Map<String,String> suffMap = new HashMap<String,String>();
static {
suffMap.put(".exe",".exe");
}
public static String filternoValidSuffix(String suffix) {
return suffMap.get(suffix);
}
/**未测试
* @param path
* @param fileType
*/
public static List<HashMap<String, String>> getFileList(String path) {
List<HashMap<String, String>> logFileList = new ArrayList<HashMap<String, String>>();
File file = new File(path);
if (file.isDirectory()) {
String fileName[] = file.list();
for (int j = 0; j < fileName.length; j++) {
File logFile = new File(path+File.separator+ fileName[j]);
HashMap<String, String> map = new HashMap<String, String>();// 存放文件信息
if (logFile.isFile()) {
map.put("fileName", logFile.getName());
map.put("fileLength", logFile.length() / 1000==0L?1+" KB":logFile.length() / 1000
+ " KB");
map.put("filePath", logFile.getPath());
map.put("lastTime", DateUtil.format(new Date(
logFile.lastModified()),
"yyyy-MM-dd hh:mm:ss"));
logFileList.add(map);
}
if(logFile.isDirectory()){
getFileList(path+File.separator+logFile.getName());
}
}
}
return logFileList;
}
/**
* 返回文件最后创建时间距离当前间隔的毫秒数
* @param file
* @return
*/
public static Long ModifyCompleteMillseconds(File file){
return System.currentTimeMillis() - file.lastModified();
}
/**
* 写文件
* @param upload
* @param fileName
*/
public static String writerFile(File upload,String fileName) throws Exception {
InputStream is = null;
OutputStream ops = null;
String resultFile = null;;
try {
if (upload != null) {
String suffix = fileName.substring(fileName.lastIndexOf("."), fileName.length()).toLowerCase(); // 取文件后缀
String saveFileName = DateUtil.toStringNoInterval(new Date(),8)+"_" + System.currentTimeMillis() + suffix;
WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
TrustConfig trustConfig = (TrustConfig)wac.getBean(ProConstants.configBeanName);//模块配置文件
if (upload.exists()){ //判断文件不存在,上传的附件大小为0视为不存在。
is = new FileInputStream(upload);
// 将文件名称放入的根目录下的upload文件下
FileUtil.createDir(new File(trustConfig.getTrustProselectCustFilePath()));
//File destFile = new File(trustConfig.getTrustProselectCustFilePath() + "/" + saveFileName);
File destFile = new File(trustConfig.getTrustProselectCustFilePath() + saveFileName); //配置文件中统一加了/
ops = new FileOutputStream(destFile);
byte[] b = new byte[8192];
int length = 0;
while ((length = is.read(b)) > 0) {
// 将数据写入流
ops.write(b, 0, length);
}
resultFile = saveFileName;
}
}
}catch(Exception e){
throw e;
}finally {
if(null != is) {
is.close();
}if(null != ops) {
ops.close();
}
}
return resultFile;
}
/**
* 描述:读取文件返回字节数组
*
**/
public static byte[] readFileByBinary(File file){
FileInputStream fis = null;
ByteBuffer buffer = null;
ByteBuffer tmp = null;
try{
fis = new FileInputStream(file);
buffer = ByteBuffer.allocate(fis.available());
tmp = ByteBuffer.allocate(BUFFER);
FileChannel channel = fis.getChannel();
while(channel.read(tmp)!=-1){
tmp.flip();
buffer.put(tmp);
tmp.clear();
}
}catch(Exception e){
throw new RuntimeException(e);
}finally{
if(fis!=null){
try {
fis.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
fis = null;
}
}
return buffer.array();
}
}
代码当中有时间的操作,请查看下一篇文章,时间操作工具类