文件相关操作工具类——FileUtils.java

文件相关操作的工具类,创建文件、删除文件、删除目录、复制、移动文件、获取文件路径、获取目录下文件个数等,满足大多数系统需求。

源码如下:(点击下载 FileUtils.java

  1 import java.io.BufferedReader;
  2 import java.io.BufferedWriter;
  3 import java.io.File;
  4 import java.io.FileInputStream;
  5 import java.io.FileNotFoundException;
  6 import java.io.FileOutputStream;
  7 import java.io.FileReader;
  8 import java.io.FileWriter;
  9 import java.io.IOException;
 10 import java.io.InputStream;
 11 import java.io.Serializable;
 12 import java.nio.CharBuffer;
 13 import java.nio.MappedByteBuffer;
 14 import java.nio.channels.FileChannel;
 15 import java.nio.charset.Charset;
 16 import java.nio.charset.CharsetDecoder;
 17 import java.text.SimpleDateFormat;
 18 import java.util.ArrayList;
 19 import java.util.Date;
 20 import java.util.HashMap;
 21 import java.util.List;
 22 import java.util.regex.Pattern;
 23 
 24 /**
 25  * 用于文件相关操作的工具类
 26  * 
 27  * 作者: zhoubang 日期:2015年8月7日 上午10:55:15
 28  */
 29 public final class FileUtils implements Serializable {
 30     private static final long serialVersionUID = 6841417839693317734L;
 31 
 32     private FileUtils() {
 33     }
 34 
 35     /**
 36      * 得到文件的输入流,如无法定位文件返回null。
 37      * 
 38      * @param relativePath
 39      *            文件相对当前应用程序的类加载器的路径。
 40      * @return 文件的输入流。
 41      */
 42     public static InputStream getResourceStream(String relativePath) {
 43         return Thread.currentThread().getContextClassLoader().getResourceAsStream(relativePath);
 44     }
 45 
 46     /**
 47      * 关闭输入流。
 48      * 
 49      * @param is 输入流,可以是null。
 50      */
 51     public static void closeInputStream(InputStream is) {
 52         if (is != null) {
 53             try {
 54                 is.close();
 55             } catch (IOException e) {
 56             }
 57         }
 58     }
 59 
 60     public static void closeFileOutputStream(FileOutputStream fos) {
 61         if (fos != null) {
 62             try {
 63                 fos.close();
 64             } catch (IOException e) {
 65             }
 66         }
 67     }
 68 
 69     /**
 70      * 从文件路径中提取目录路径,如果文件路径不含目录返回null。
 71      * 
 72      * @param filePath 文件路径。
 73      * @return 目录路径,不以'/'或操作系统的文件分隔符结尾。
 74      */
 75     public static String extractDirPath(String filePath) {
 76         int separatePos = Math.max(filePath.lastIndexOf('/'), filePath.lastIndexOf('\')); // 分隔目录和文件名的位置
 77         return separatePos == -1 ? null : filePath.substring(0, separatePos);
 78     }
 79 
 80     /**
 81      * 从文件路径中提取文件名, 如果不含分隔符返回null
 82      * 
 83      * @param filePath
 84      * @return 文件名, 如果不含分隔符返回null
 85      */
 86     public static String extractFileName(String filePath) {
 87         int separatePos = Math.max(filePath.lastIndexOf('/'), filePath.lastIndexOf('\')); // 分隔目录和文件名的位置
 88         return separatePos == -1 ? null : filePath.substring(separatePos + 1, filePath.length());
 89     }
 90 
 91     /**
 92      * 按路径建立文件,如已有相同路径的文件则不建立。
 93      * 
 94      * @param filePath 要建立文件的路径。
 95      * @return 表示此文件的File对象。
 96      * @throws IOException 如路径是目录或建文件时出错抛异常。
 97      */
 98     public static File makeFile(String filePath) {
 99         File file = new File(filePath);
100         if (file.isFile())
101             return file;
102         if (filePath.endsWith("/") || filePath.endsWith("\"))
103             try {
104                 throw new IOException(filePath + " is a directory");
105             } catch (IOException e) {
106                 e.printStackTrace();
107             }
108 
109         String dirPath = extractDirPath(filePath); // 文件所在目录的路径
110 
111         if (dirPath != null) { // 如文件所在目录不存在则先建目录
112             makeFolder(dirPath);
113         }
114 
115         try {
116             file.createNewFile();
117         } catch (IOException e) {
118             e.printStackTrace();
119         }
120         // log4j.info("Folder has been created: " + filePath);
121         // System.out.println("文件已创建: " + filePath);
122         return file;
123     }
124 
125     /**
126      * 新建目录,支持建立多级目录
127      * 
128      * @param folderPath 新建目录的路径字符串
129      * @return boolean,如果目录创建成功返回true,否则返回false
130      */
131     public static boolean makeFolder(String folderPath) {
132         try {
133             File myFilePath = new File(folderPath);
134             if (!myFilePath.exists()) {
135                 myFilePath.mkdirs();
136                 // System.out.println("新建目录为:" + folderPath);
137                 // log4j.info("Create new folder:" + folderPath);
138             } else {
139                 // System.out.println("目录已经存在: " + folderPath);
140                 // log4j.info("Folder is existed:" + folderPath);
141             }
142         } catch (Exception e) {
143             // System.out.println("新建目录操作出错");
144             e.printStackTrace();
145             // log4j.error("Create new folder error: " + folderPath);
146             return false;
147         }
148         return true;
149     }
150 
151     /**
152      * 删除文件
153      * 
154      * @param filePathAndName 要删除文件名及路径
155      * @return boolean 删除成功返回true,删除失败返回false
156      */
157     public static boolean deleteFile(String filePathAndName) {
158         try {
159             File myDelFile = new File(filePathAndName);
160             if (myDelFile.exists()) {
161                 myDelFile.delete();
162                 // log4j.info("File:" + filePathAndName +
163                 // " has been deleted!!!");
164             }
165         } catch (Exception e) {
166             e.printStackTrace();
167             // log4j.error("Error delete file:" + filePathAndName);
168             return false;
169         }
170         return true;
171     }
172 
173     /**
174      * 递归删除指定目录中所有文件和子文件夹
175      * 
176      * @param path
177      *            某一目录的路径,如"c:cs"
178      * @param ifDeleteFolder
179      *            boolean值,如果传true,则删除目录下所有文件和文件夹;如果传false,则只删除目录下所有文件,子文件夹将保留
180      */
181     public static void deleteAllFile(String path, boolean ifDeleteFolder) {
182         File file = new File(path);
183         if (!file.exists()) {
184             return;
185         }
186         if (!file.isDirectory()) {
187             return;
188         }
189         String[] tempList = file.list();
190         String temp = null;
191         for (int i = 0; i < tempList.length; i++) {
192             if (path.endsWith("\") || path.endsWith("/"))
193                 temp = path + tempList[i];
194             else
195                 temp = path + File.separator + tempList[i];
196             if ((new File(temp)).isFile()) {
197                 deleteFile(temp);
198             } else if ((new File(temp)).isDirectory() && ifDeleteFolder) {
199                 deleteAllFile(path + File.separator + tempList[i], ifDeleteFolder);// 先删除文件夹里面的文件
200                 deleteFolder(path + File.separator + tempList[i]);// 再删除空文件夹
201             }
202         }
203     }
204 
205     /**
206      * 删除文件夹,包括里面的文件
207      * 
208      * @param folderPath 文件夹路径字符串
209      */
210     public static void deleteFolder(String folderPath) {
211         try {
212             File myFilePath = new File(folderPath);
213             if (myFilePath.exists()) {
214                 deleteAllFile(folderPath, true); // 删除完里面所有内容
215                 myFilePath.delete(); // 删除空文件夹
216             }
217             // log4j.info("ok!Delete folder success: " + folderPath);
218         } catch (Exception e) {
219             e.printStackTrace();
220             // log4j.error("Delete folder fail: " + folderPath);
221         }
222     }
223 
224     /**
225      * 复制文件,如果目标文件的路径不存在,会自动新建路径
226      * 
227      * @param sourcePath
228      *            源文件路径, e.g. "c:/cs.txt"
229      * @param targetPath
230      *            目标文件路径 e.g. "f:/bb/cs.txt"
231      */
232     public static void copyFile(String sourcePath, String targetPath) {
233         InputStream inStream = null;
234         FileOutputStream fos = null;
235         try {
236             int byteSum = 0;
237             int byteRead = 0;
238             File sourcefile = new File(sourcePath);
239             if (sourcefile.exists()) { // 文件存在时
240                 inStream = new FileInputStream(sourcePath); // 读入原文件
241                 String dirPath = extractDirPath(targetPath); // 文件所在目录的路径
242                 if (dirPath != null) { // 如文件所在目录不存在则先建目录
243                     makeFolder(dirPath);
244                 }
245                 fos = new FileOutputStream(targetPath);
246                 byte[] buffer = new byte[1444];
247                 while ((byteRead = inStream.read(buffer)) != -1) {
248                     byteSum += byteRead; // 字节数 文件大小
249                     fos.write(buffer, 0, byteRead);
250                 }
251                 System.out.println("File size is: " + byteSum);
252 
253                 // log4j.info("Source path is -->" + sourcePath);
254                 // log4j.info("Target path is-->" + targetPath);
255                 // log4j.info("File size is-->" + byteSum);
256 
257             }
258         } catch (Exception e) {
259             e.printStackTrace();
260             // log4j.debug("Copy single file fail: " + sourcePath);
261         } finally {
262             closeInputStream(inStream);
263             closeFileOutputStream(fos);
264         }
265     }
266 
267     /**
268      * 将路径和文件名拼接起来
269      * 
270      * @param folderPath
271      *            某一文件夹路径字符串,e.g. "c:cs" 或 "c:cs"
272      * @param fileName
273      *            某一文件名字符串, e.g. "cs.txt"
274      * @return 文件全路径的字符串
275      */
276     public static String makeFilePath(String folderPath, String fileName) {
277         return folderPath.endsWith("\") || folderPath.endsWith("/") ? folderPath + fileName : folderPath + File.separatorChar + fileName;
278     }
279 
280     /**
281      * 将某一文件夹下的所有文件和子文件夹拷贝到目标文件夹,若目标文件夹不存在将自动创建
282      * 
283      * @param sourcePath
284      *            源文件夹字符串,e.g. "c:cs"
285      * @param targetPath
286      *            目标文件夹字符串,e.g. "d:	tqq"
287      */
288     @SuppressWarnings("unused")
289     public static void copyFolder(String sourcePath, String targetPath) {
290         FileInputStream input = null;
291         FileOutputStream output = null;
292         try {
293             makeFolder(targetPath); // 如果文件夹不存在 则建立新文件夹
294             String[] file = new File(sourcePath).list();
295             File temp = null;
296             for (int i = 0; i < file.length; i++) {
297                 String tempPath = makeFilePath(sourcePath, file[i]);
298                 temp = new File(tempPath);
299                 String target = "";
300                 if (temp.isFile()) {
301                     input = new FileInputStream(temp);
302                     output = new FileOutputStream(target = makeFilePath(targetPath, file[i]));
303                     byte[] b = new byte[1024 * 5];
304                     int len = 0;
305                     int sum = 0;
306                     while ((len = input.read(b)) != -1) {
307                         output.write(b, 0, len);
308                         sum += len;
309                     }
310                     target = target + "";
311                     output.flush();
312                     closeInputStream(input);
313                     closeFileOutputStream(output);
314 
315                     // log4j.info("Source path-->" + tempPath);
316                     // log4j.info("Target path-->" + target);
317                     // log4j.info("File size-->" + sum);
318 
319                 } else if (temp.isDirectory()) {// 如果是子文件夹
320                     copyFolder(sourcePath + '/' + file[i], targetPath + '/' + file[i]);
321                 }
322             }
323         } catch (Exception e) {
324             // log4j.info("Copy all the folder fail!");
325             e.printStackTrace();
326         } finally {
327             closeInputStream(input);
328             closeFileOutputStream(output);
329         }
330     }
331 
332     /**
333      * 移动文件
334      * 
335      * @param oldFilePath
336      *            旧文件路径字符串, e.g. "c:	tcs.txt"
337      * @param newFilePath
338      *            新文件路径字符串, e.g. "d:kkcs.txt"
339      */
340     public static void moveFile(String oldFilePath, String newFilePath) {
341         copyFile(oldFilePath, newFilePath);
342         deleteFile(oldFilePath);
343     }
344 
345     /**
346      * 移动文件夹
347      * 
348      * @param oldFolderPath
349      *            旧文件夹路径字符串,e.g. "c:cs"
350      * @param newFolderPath
351      *            新文件夹路径字符串,e.g. "d:cs"
352      */
353     public static void moveFolder(String oldFolderPath, String newFolderPath) {
354         copyFolder(oldFolderPath, newFolderPath);
355         deleteFolder(oldFolderPath);
356 
357     }
358 
359     /**
360      * 获得某一文件夹下的所有文件的路径集合
361      * 
362      * @param filePath
363      *            文件夹路径
364      * @return ArrayList,其中的每个元素是一个文件的路径的字符串
365      */
366     public static ArrayList<String> getFilePathFromFolder(String filePath) {
367         ArrayList<String> fileNames = new ArrayList<String>();
368         File file = new File(filePath);
369         try {
370             File[] tempFile = file.listFiles();
371             for (int i = 0; i < tempFile.length; i++) {
372                 if (tempFile[i].isFile()) {
373                     String tempFileName = tempFile[i].getName();
374                     fileNames.add(makeFilePath(filePath, tempFileName));
375                 }
376             }
377         } catch (Exception e) {
378             // fileNames.add("尚无文件到达!");
379             // e.printStackTrace();
380             // log4j.info("Can not find files!"+e.getMessage());
381         }
382         return fileNames;
383     }
384 
385     /**
386      * 递归遍历文件目录,获取所有文件路径
387      * 
388      * @param filePath
389      * @return 2012-1-4
390      */
391     public static ArrayList<String> getAllFilePathFromFolder(String filePath) {
392         ArrayList<String> filePaths = new ArrayList<String>();
393         File file = new File(filePath);
394         try {
395             File[] tempFile = file.listFiles();
396             for (int i = 0; i < tempFile.length; i++) {
397                 String tempFileName = tempFile[i].getName();
398                 String path = makeFilePath(filePath, tempFileName);
399                 if (tempFile[i].isFile()) {
400                     filePaths.add(path);
401                 } else {
402                     ArrayList<String> tempFilePaths = getAllFilePathFromFolder(path);
403                     if (tempFilePaths.size() > 0) {
404                         for (String tempPath : tempFilePaths) {
405                             filePaths.add(tempPath);
406                         }
407                     }
408                 }
409             }
410         } catch (Exception e) {
411             // fileNames.add("尚无文件到达!");
412             // e.printStackTrace();
413             // log4j.info("Can not find files!"+e.getMessage());
414         }
415         return filePaths;
416     }
417 
418     /**
419      * 获得某一文件夹下的所有TXT,txt文件名的集合
420      * 
421      * @param filePath
422      *            文件夹路径
423      * @return ArrayList,其中的每个元素是一个文件名的字符串
424      */
425     @SuppressWarnings("rawtypes")
426     public static ArrayList getFileNameFromFolder(String filePath) {
427         ArrayList<String> fileNames = new ArrayList<String>();
428         File file = new File(filePath);
429         File[] tempFile = file.listFiles();
430         for (int i = 0; i < tempFile.length; i++) {
431             if (tempFile[i].isFile())
432                 fileNames.add(tempFile[i].getName());
433         }
434         return fileNames;
435     }
436 
437     /**
438      * 获得某一文件夹下的所有文件的总数
439      * 
440      * @param filePath
441      *            文件夹路径
442      * @return int 文件总数
443      */
444     public static int getFileCount(String filePath) {
445         int count = 0;
446         try {
447             File file = new File(filePath);
448             if (!isFolderExist(filePath))
449                 return count;
450             File[] tempFile = file.listFiles();
451             for (int i = 0; i < tempFile.length; i++) {
452                 if (tempFile[i].isFile())
453                     count++;
454             }
455         } catch (Exception fe) {
456             count = 0;
457         }
458         return count;
459     }
460 
461     /**
462      * 获得某一路径下要求匹配的文件的个数
463      * 
464      * @param filePath
465      *            文件夹路径
466      * @param matchs
467      *            需要匹配的文件名字符串,如".*a.*",如果传空字符串则不做匹配工作 直接返回路径下的文件个数
468      * @return int 匹配文件名的文件总数
469      */
470     public static int getFileCount(String filePath, String matchs) {
471         int count = 0;
472         if (!isFolderExist(filePath))
473             return count;
474         if (matchs.equals("") || matchs == null)
475             return getFileCount(filePath);
476         File file = new File(filePath);
477         // log4j.info("filePath in getFileCount: " + filePath);
478         // log4j.info("matchs in getFileCount: " + matchs);
479         File[] tempFile = file.listFiles();
480         for (int i = 0; i < tempFile.length; i++) {
481             if (tempFile[i].isFile())
482                 if (Pattern.matches(matchs, tempFile[i].getName()))
483                     count++;
484         }
485         return count;
486     }
487 
488     public static int getStrCountFromFile(String filePath, String str) {
489         if (!isFileExist(filePath))
490             return 0;
491         FileReader fr = null;
492         BufferedReader br = null;
493         int count = 0;
494         try {
495             fr = new FileReader(filePath);
496             br = new BufferedReader(fr);
497             String line = null;
498             while ((line = br.readLine()) != null) {
499                 if (line.indexOf(str) != -1)
500                     count++;
501             }
502         } catch (FileNotFoundException e) {
503             e.printStackTrace();
504         } catch (IOException e) {
505             e.printStackTrace();
506         } finally {
507             try {
508                 if (br != null)
509                     br.close();
510                 if (fr != null)
511                     fr.close();
512             } catch (Exception e) {
513                 e.printStackTrace();
514             }
515         }
516         return count;
517     }
518 
519     /**
520      * 获得某一文件的行数
521      * 
522      * @param filePath
523      *            文件夹路径
524      * 
525      * @return int 行数
526      */
527     public static int getFileLineCount(String filePath) {
528         if (!isFileExist(filePath))
529             return 0;
530         FileReader fr = null;
531         BufferedReader br = null;
532         int count = 0;
533         try {
534             fr = new FileReader(filePath);
535             br = new BufferedReader(fr);
536             while ((br.readLine()) != null) {
537                 count++;
538             }
539         } catch (FileNotFoundException e) {
540             e.printStackTrace();
541         } catch (IOException e) {
542             e.printStackTrace();
543         } finally {
544             try {
545                 if (br != null)
546                     br.close();
547                 if (fr != null)
548                     fr.close();
549             } catch (Exception e) {
550                 e.printStackTrace();
551             }
552         }
553         return count;
554     }
555 
556     /**
557      * 判断某一文件是否为空
558      * 
559      * @param filePath 文件的路径字符串,e.g. "c:cs.txt"
560      * @return 如果文件为空返回true, 否则返回false
561      * @throws IOException
562      */
563     public static boolean ifFileIsNull(String filePath) throws IOException {
564         boolean result = false;
565         FileReader fr = new FileReader(filePath);
566         if (fr.read() == -1) {
567             result = true;
568             // log4j.info(filePath + " is null!");
569         } else {
570             // log4j.info(filePath + " not null!");
571         }
572         fr.close();
573         return result;
574     }
575 
576     /**
577      * 判断文件是否存在
578      * 
579      * @param fileName 文件路径字符串,e.g. "c:cs.txt"
580      * @return 若文件存在返回true,否则返回false
581      */
582     public static boolean isFileExist(String fileName) {
583         // 判断文件名是否为空
584         if (fileName == null || fileName.length() == 0) {
585             // log4j.error("File length is 0!");
586             return false;
587         } else {
588             // 读入文件 判断文件是否存在
589             File file = new File(fileName);
590             if (!file.exists() || file.isDirectory()) {
591                 // log4j.error(fileName + "is not exist!");
592                 return false;
593             }
594         }
595         return true;
596     }
597 
598     /**
599      * 判断文件夹是否存在
600      * 
601      * @param folderPath 文件夹路径字符串,e.g. "c:cs"
602      * @return 若文件夹存在返回true, 否则返回false
603      */
604     public static boolean isFolderExist(String folderPath) {
605         File file = new File(folderPath);
606         return file.isDirectory() ? true : false;
607     }
608 
609     /**
610      * 获得文件的大小
611      * 
612      * @param filePath 文件路径字符串,e.g. "c:cs.txt"
613      * @return 返回文件的大小,单位kb,如果文件不存在返回null
614      */
615     public static Double getFileSize(String filePath) {
616         if (!isFileExist(filePath))
617             return null;
618         else {
619             File file = new File(filePath);
620             double intNum = Math.ceil(file.length() / 1024.0);
621             return new Double(intNum);
622         }
623 
624     }
625 
626     /**
627      * 获得文件的大小,字节表示
628      * 
629      * @param filePath 文件路径字符串,e.g. "c:cs.txt"
630      * @return 返回文件的大小,单位kb,如果文件不存在返回null
631      */
632     public static Double getFileByteSize(String filePath) {
633         if (!isFileExist(filePath))
634             return null;
635         else {
636             File file = new File(filePath);
637             double intNum = Math.ceil(file.length());
638             return new Double(intNum);
639         }
640 
641     }
642 
643     /**
644      * 获得外汇牌价文件的大小(字节)
645      * 
646      * @param filePath 文件路径字符串,e.g. "c:cs.txt"
647      * @return 返回文件的大小,单位kb,如果文件不存在返回null
648      */
649     public static Double getWhpjFileSize(String filePath) {
650         if (!isFileExist(filePath))
651             return null;
652         else {
653             File file = new File(filePath);
654             return new Double(file.length());
655         }
656 
657     }
658 
659     /**
660      * 获得文件的最后修改时间
661      * 
662      * @param filePath 文件路径字符串,e.g. "c:cs.txt"
663      * @return 返回文件最后的修改日期的字符串,如果文件不存在返回null
664      */
665     public static String fileModifyTime(String filePath) {
666         if (!isFileExist(filePath))
667             return null;
668         else {
669             File file = new File(filePath);
670 
671             long timeStamp = file.lastModified();
672             SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm");
673             String tsForm = formatter.format(new Date(timeStamp));
674             return tsForm;
675         }
676     }
677 
678     /**
679      * 遍历某一文件夹下的所有文件,返回一个ArrayList,每个元素又是一个子ArrayList,
680      * 子ArrayList包含三个字段,依次是文件的全路径(String),文件的修改日期(String), 文件的大小(Double)
681      * 
682      * @param folderPath 某一文件夹的路径
683      * @return ArrayList
684      */
685     @SuppressWarnings({ "unchecked", "rawtypes" })
686     public static ArrayList getFilesSizeModifyTime(String folderPath) {
687         List returnList = new ArrayList();
688         List filePathList = getFilePathFromFolder(folderPath);
689         for (int i = 0; i < filePathList.size(); i++) {
690             List tempList = new ArrayList();
691             String filePath = (String) filePathList.get(i);
692             String modifyTime = FileUtils.fileModifyTime(filePath);
693             Double fileSize = FileUtils.getFileSize(filePath);
694             tempList.add(filePath);
695             tempList.add(modifyTime);
696             tempList.add(fileSize);
697             returnList.add(tempList);
698         }
699         return (ArrayList) returnList;
700     }
701 
702     /**
703      * 获得某一文件夹下的所有TXT,txt文件名的集合
704      * 
705      * @param filePath
706      *            文件夹路径
707      * @return ArrayList,其中的每个元素是一个文件名的字符串
708      */
709     @SuppressWarnings({ "unchecked", "rawtypes" })
710     public static ArrayList getTxtFileNameFromFolder(String filePath) {
711         ArrayList fileNames = new ArrayList();
712         File file = new File(filePath);
713         File[] tempFile = file.listFiles();
714         for (int i = 0; i < tempFile.length; i++) {
715             if (tempFile[i].isFile())
716                 if (tempFile[i].getName().indexOf("TXT") != -1 || tempFile[i].getName().indexOf("txt") != -1) {
717                     fileNames.add(tempFile[i].getName());
718                 }
719         }
720         return fileNames;
721     }
722 
723     /**
724      * 获得某一文件夹下的所有xml,XML文件名的集合
725      * 
726      * @param filePath
727      *            文件夹路径
728      * @return ArrayList,其中的每个元素是一个文件名的字符串
729      */
730     @SuppressWarnings({ "unchecked", "rawtypes" })
731     public static ArrayList getXmlFileNameFromFolder(String filePath) {
732         ArrayList fileNames = new ArrayList();
733         File file = new File(filePath);
734         File[] tempFile = file.listFiles();
735         for (int i = 0; i < tempFile.length; i++) {
736             if (tempFile[i].isFile())
737                 if (tempFile[i].getName().indexOf("XML") != -1 || tempFile[i].getName().indexOf("xml") != -1) {
738                     fileNames.add(tempFile[i].getName());
739                 }
740         }
741         return fileNames;
742     }
743 
744     /**
745      * 校验文件是否存在
746      *
747      * @param fileName
748      *            String 文件名称
749      * @param mapErrorMessage
750      *            Map 错误信息Map集
751      * @return boolean 校验值
752      */
753     @SuppressWarnings({ "unchecked", "rawtypes" })
754     public static boolean checkFile(String fileName, HashMap mapErrorMessage) {
755         if (mapErrorMessage == null)
756             mapErrorMessage = new HashMap();
757         // 判断文件名是否为空
758         if (fileName == null) {
759             fileName = "";
760         }
761         // 判断文件名长度是否为0
762         if (fileName.length() == 0) {
763             mapErrorMessage.put("errorMessage", "fileName length is 0");
764             return false;
765         } else {
766             // 读入文件 判断文件是否存在
767             File file = new File(fileName);
768             if (!file.exists() || file.isDirectory()) {
769                 mapErrorMessage.put("errorMessage", fileName + "is not exist!");
770                 return false;
771             }
772         }
773         return true;
774     }
775 
776     /**
777      * 校验文件是否存在 add by fzhang
778      * 
779      * @param fileName
780      *            String 文件名称
781      * @return boolean 校验值
782      */
783     public static boolean checkFile(String fileName) {
784         // 判断文件名是否为空
785         if (fileName == null) {
786             fileName = "";
787         }
788         // 判断文件名长度是否为0
789         if (fileName.length() == 0) {
790 
791             // log4j.info("File name length is 0.");
792             return false;
793         } else {
794             // 读入文件 判断文件是否存在
795             File file = new File(fileName);
796             if (!file.exists() || file.isDirectory()) {
797                 // log4j.info(fileName +"is not exist!");
798                 return false;
799             }
800         }
801         return true;
802     }
803 
804     /**
805      * 新建目录
806      * 
807      * @param folderPath
808      *            String 如 c:/fqf
809      * @return boolean
810      */
811     public static void newFolder(String folderPath) {
812         try {
813             String filePath = folderPath;
814             filePath = filePath.toString();
815             java.io.File myFilePath = new java.io.File(filePath);
816             if (!myFilePath.exists()) {
817                 myFilePath.mkdir();
818             }
819         } catch (Exception e) {
820             System.out.println("新建目录操作出错");
821             e.printStackTrace();
822         }
823     }
824 
825     /**
826      * 重新缓存发送失败的缓存文件
827      * 
828      * @author Herman.Xiong
829      * @throws IOException
830      */
831     @SuppressWarnings({ "unchecked", "rawtypes" })
832     public static void sessionData(String path, List<List> list)
833             throws IOException {
834 
835         BufferedWriter bw = new BufferedWriter(new FileWriter(path));
836 
837         for (List<String> tempList : list) {
838 
839             for (String str : tempList) {
840                 if (str != null && !str.equals("")) {
841                     bw.write(str);
842                     bw.newLine();
843                     bw.flush();
844                 }
845             }
846         }
847         bw.close();
848     }
849 
850     /**
851      * 在指定的文本中对比数据
852      * 
853      * @param urladdr
854      * @param filePath
855      * @return boolean
856      */
857     public static boolean compareUrl(String urladdr, String filePath, FileChannel fc) {
858         boolean isExist = false;
859         Charset charset = Charset.forName("UTF-8");
860         CharsetDecoder decoder = charset.newDecoder();
861         try {
862             int sz = (int) fc.size();
863             MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz);
864             CharBuffer cb = decoder.decode(bb);
865             String s = String.valueOf(cb);
866             int n = s.indexOf(urladdr);
867             if (n > -1) {
868                 // log4j.info(filePath + " the article already exists " +
869                 // urladdr);
870             } else {
871                 isExist = true;
872             }
873         } catch (Exception e) {
874             // log4j.error("document alignment error" + e);
875         } finally {
876             try {
877                 // if(!Util.isEmpty(fc))
878                 // {
879                 // fc.close();
880                 // }
881                 // if(!Util.isEmpty(fis))
882                 // {
883                 // fis.close();
884                 // }
885             } catch (Exception e2) {
886                 // log4j.error(e2);
887             }
888         }
889         return isExist;
890     }
891 
892 }
原文地址:https://www.cnblogs.com/zhoubang521/p/5200035.html