码迷,mamicode.com
首页 > 其他好文 > 详细

FileUtil

时间:2014-11-12 22:43:27      阅读:263      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   io   color   ar   os   使用   java   

  1 package com.gootrip.util;
  2 
  3 import java.io.BufferedReader;
  4 import java.io.File;
  5 import java.io.FileInputStream;
  6 import java.io.FileOutputStream;
  7 import java.io.FileReader;
  8 import java.io.FileWriter;
  9 import java.io.FilenameFilter;
 10 import java.io.IOException;
 11 import java.net.MalformedURLException;
 12 import java.net.URL;
 13 import java.util.ArrayList;
 14 import java.util.Enumeration;
 15 import java.util.Hashtable;
 16 
 17 import javax.swing.filechooser.FileFilter;
 18 
 19 /**
 20  * 此类中封装一些常用的文件操作。
 21  * 所有方法都是静态方法,不需要生成此类的实例,
 22  * 为避免生成此类的实例,构造方法被申明为private类型的。
 23  * @since  1.0
 24  */
 25 
 26 public class FileUtil {
 27   /**
 28    * 私有构造方法,防止类的实例化,因为工具类不需要实例化。
 29    */
 30   private FileUtil() {
 31 
 32   }
 33 
 34   /**
 35    * 修改文件的最后访问时间。
 36    * 如果文件不存在则创建该文件。
 37    * <b>目前这个方法的行为方式还不稳定,主要是方法有些信息输出,这些信息输出是否保留还在考虑中。</b>
 38    * @param file 需要修改最后访问时间的文件。
 39    * @since  1.0
 40    */
 41   public static void touch(File file) {
 42     long currentTime = System.currentTimeMillis();
 43     if (!file.exists()) {
 44       System.err.println("file not found:" + file.getName());
 45       System.err.println("Create a new file:" + file.getName());
 46       try {
 47         if (file.createNewFile()) {
 48           System.out.println("Succeeded!");
 49         }
 50         else {
 51           System.err.println("Create file failed!");
 52         }
 53       }
 54       catch (IOException e) {
 55         System.err.println("Create file failed!");
 56         e.printStackTrace();
 57       }
 58     }
 59     boolean result = file.setLastModified(currentTime);
 60     if (!result) {
 61       System.err.println("touch failed: " + file.getName());
 62     }
 63   }
 64 
 65   /**
 66    * 修改文件的最后访问时间。
 67    * 如果文件不存在则创建该文件。
 68    * <b>目前这个方法的行为方式还不稳定,主要是方法有些信息输出,这些信息输出是否保留还在考虑中。</b>
 69    * @param fileName 需要修改最后访问时间的文件的文件名。
 70    * @since  1.0
 71    */
 72   public static void touch(String fileName) {
 73     File file = new File(fileName);
 74     touch(file);
 75   }
 76 
 77   /**
 78    * 修改文件的最后访问时间。
 79    * 如果文件不存在则创建该文件。
 80    * <b>目前这个方法的行为方式还不稳定,主要是方法有些信息输出,这些信息输出是否保留还在考虑中。</b>
 81    * @param files 需要修改最后访问时间的文件数组。
 82    * @since  1.0
 83    */
 84   public static void touch(File[] files) {
 85     for (int i = 0; i < files.length; i++) {
 86       touch(files[i]);
 87     }
 88   }
 89 
 90   /**
 91    * 修改文件的最后访问时间。
 92    * 如果文件不存在则创建该文件。
 93    * <b>目前这个方法的行为方式还不稳定,主要是方法有些信息输出,这些信息输出是否保留还在考虑中。</b>
 94    * @param fileNames 需要修改最后访问时间的文件名数组。
 95    * @since  1.0
 96    */
 97   public static void touch(String[] fileNames) {
 98     File[] files = new File[fileNames.length];
 99     for (int i = 0; i < fileNames.length; i++) {
100       files[i] = new File(fileNames[i]);
101     }
102     touch(files);
103   }
104 
105   /**
106    * 判断指定的文件是否存在。
107    * @param fileName 要判断的文件的文件名
108    * @return 存在时返回true,否则返回false。
109    * @since  1.0
110    */
111   public static boolean isFileExist(String fileName) {
112     return new File(fileName).isFile();
113   }
114 
115   /**
116    * 创建指定的目录。
117    * 如果指定的目录的父目录不存在则创建其目录书上所有需要的父目录。
118    * <b>注意:可能会在返回false的时候创建部分父目录。</b>
119    * @param file 要创建的目录
120    * @return 完全创建成功时返回true,否则返回false。
121    * @since  1.0
122    */
123   public static boolean makeDirectory(File file) {
124     File parent = file.getParentFile();
125     if (parent != null) {
126       return parent.mkdirs();
127     }
128     return false;
129   }
130 
131   /**
132    * 创建指定的目录。
133    * 如果指定的目录的父目录不存在则创建其目录书上所有需要的父目录。
134    * <b>注意:可能会在返回false的时候创建部分父目录。</b>
135    * @param fileName 要创建的目录的目录名
136    * @return 完全创建成功时返回true,否则返回false。
137    * @since  1.0
138    */
139   public static boolean makeDirectory(String fileName) {
140     File file = new File(fileName);
141     return makeDirectory(file);
142   }
143 
144   /**
145    * 清空指定目录中的文件。
146    * 这个方法将尽可能删除所有的文件,但是只要有一个文件没有被删除都会返回false。
147    * 另外这个方法不会迭代删除,即不会删除子目录及其内容。
148    * @param directory 要清空的目录
149    * @return 目录下的所有文件都被成功删除时返回true,否则返回false.
150    * @since  1.0
151    */
152   public static boolean emptyDirectory(File directory) {
153     boolean result = true;
154     File[] entries = directory.listFiles();
155     for (int i = 0; i < entries.length; i++) {
156       if (!entries[i].delete()) {
157         result = false;
158       }
159     }
160     return result;
161   }
162 
163   /**
164    * 清空指定目录中的文件。
165    * 这个方法将尽可能删除所有的文件,但是只要有一个文件没有被删除都会返回false。
166    * 另外这个方法不会迭代删除,即不会删除子目录及其内容。
167    * @param directoryName 要清空的目录的目录名
168    * @return 目录下的所有文件都被成功删除时返回true,否则返回false。
169    * @since  1.0
170    */
171   public static boolean emptyDirectory(String directoryName) {
172     File dir = new File(directoryName);
173     return emptyDirectory(dir);
174   }
175 
176   /**
177    * 删除指定目录及其中的所有内容。
178    * @param dirName 要删除的目录的目录名
179    * @return 删除成功时返回true,否则返回false。
180    * @since  1.0
181    */
182   public static boolean deleteDirectory(String dirName) {
183     return deleteDirectory(new File(dirName));
184   }
185 
186   /**
187    * 删除指定目录及其中的所有内容。
188    * @param dir 要删除的目录
189    * @return 删除成功时返回true,否则返回false。
190    * @since  1.0
191    */
192   public static boolean deleteDirectory(File dir) {
193     if ( (dir == null) || !dir.isDirectory()) {
194       throw new IllegalArgumentException("Argument " + dir +
195                                          " is not a directory. ");
196     }
197 
198     File[] entries = dir.listFiles();
199     int sz = entries.length;
200 
201     for (int i = 0; i < sz; i++) {
202       if (entries[i].isDirectory()) {
203         if (!deleteDirectory(entries[i])) {
204           return false;
205         }
206       }
207       else {
208         if (!entries[i].delete()) {
209           return false;
210         }
211       }
212     }
213 
214     if (!dir.delete()) {
215       return false;
216     }
217     return true;
218   }
219 
220   /**
221    * 列出目录中的所有内容,包括其子目录中的内容。
222    * @param fileName 要列出的目录的目录名
223    * @return 目录内容的文件数组。
224    * @since  1.0
225    */
226   /*public static File[] listAll(String fileName) {
227     return listAll(new File(fileName));
228   }*/
229 
230   /**
231    * 列出目录中的所有内容,包括其子目录中的内容。
232    * @param file 要列出的目录
233    * @return 目录内容的文件数组。
234    * @since  1.0
235    */
236   /*public static File[] listAll(File file) {
237     ArrayList list = new ArrayList();
238     File[] files;
239     if (!file.exists() || file.isFile()) {
240       return null;
241     }
242     list(list, file, new AllFileFilter());
243     list.remove(file);
244     files = new File[list.size()];
245     list.toArray(files);
246     return files;
247   }*/
248 
249   /**
250    * 列出目录中的所有内容,包括其子目录中的内容。
251    * @param file 要列出的目录
252    * @param filter 过滤器
253    * @return 目录内容的文件数组。
254    * @since  1.0
255    */
256   public static File[] listAll(File file,
257                                javax.swing.filechooser.FileFilter filter) {
258     ArrayList list = new ArrayList();
259     File[] files;
260     if (!file.exists() || file.isFile()) {
261       return null;
262     }
263     list(list, file, filter);
264     files = new File[list.size()];
265     list.toArray(files);
266     return files;
267   }
268 
269   /**
270    * 将目录中的内容添加到列表。
271    * @param list 文件列表
272    * @param filter 过滤器
273    * @param file 目录
274    */
275   private static void list(ArrayList list, File file,
276                            javax.swing.filechooser.FileFilter filter) {
277     if (filter.accept(file)) {
278       list.add(file);
279       if (file.isFile()) {
280         return;
281       }
282     }
283     if (file.isDirectory()) {
284       File files[] = file.listFiles();
285       for (int i = 0; i < files.length; i++) {
286         list(list, files[i], filter);
287       }
288     }
289 
290   }
291 
292   /**
293    * 返回文件的URL地址。
294    * @param file 文件
295    * @return 文件对应的的URL地址
296    * @throws MalformedURLException
297    * @since  1.0
298    * @deprecated 在实现的时候没有注意到File类本身带一个toURL方法将文件路径转换为URL。
299    *             请使用File.toURL方法。
300    */
301   public static URL getURL(File file) throws MalformedURLException {
302     String fileURL = "file:/" + file.getAbsolutePath();
303     URL url = new URL(fileURL);
304     return url;
305   }
306 
307   /**
308    * 从文件路径得到文件名。
309    * @param filePath 文件的路径,可以是相对路径也可以是绝对路径
310    * @return 对应的文件名
311    * @since  1.0
312    */
313   public static String getFileName(String filePath) {
314     File file = new File(filePath);
315     return file.getName();
316   }
317 
318   /**
319    * 从文件名得到文件绝对路径。
320    * @param fileName 文件名
321    * @return 对应的文件路径
322    * @since  1.0
323    */
324   public static String getFilePath(String fileName) {
325     File file = new File(fileName);
326     return file.getAbsolutePath();
327   }
328 
329   /**
330    * 将DOS/Windows格式的路径转换为UNIX/Linux格式的路径。
331    * 其实就是将路径中的"\"全部换为"/",因为在某些情况下我们转换为这种方式比较方便,
332    * 某中程度上说"/"比"\"更适合作为路径分隔符,而且DOS/Windows也将它当作路径分隔符。
333    * @param filePath 转换前的路径
334    * @return 转换后的路径
335    * @since  1.0
336    */
337   public static String toUNIXpath(String filePath) {
338     return filePath.replace(‘\\‘, ‘/‘);
339   }
340 
341   /**
342    * 从文件名得到UNIX风格的文件绝对路径。
343    * @param fileName 文件名
344    * @return 对应的UNIX风格的文件路径
345    * @since  1.0
346    * @see #toUNIXpath(String filePath) toUNIXpath
347    */
348   public static String getUNIXfilePath(String fileName) {
349     File file = new File(fileName);
350     return toUNIXpath(file.getAbsolutePath());
351   }
352 
353   /**
354    * 得到文件的类型。
355    * 实际上就是得到文件名中最后一个“.”后面的部分。
356    * @param fileName 文件名
357    * @return 文件名中的类型部分
358    * @since  1.0
359    */
360   public static String getTypePart(String fileName) {
361     int point = fileName.lastIndexOf(‘.‘);
362     int length = fileName.length();
363     if (point == -1 || point == length - 1) {
364       return "";
365     }
366     else {
367       return fileName.substring(point + 1, length);
368     }
369   }
370 
371   /**
372    * 得到文件的类型。
373    * 实际上就是得到文件名中最后一个“.”后面的部分。
374    * @param file 文件
375    * @return 文件名中的类型部分
376    * @since  1.0
377    */
378   public static String getFileType(File file) {
379     return getTypePart(file.getName());
380   }
381 
382   /**
383    * 得到文件的名字部分。
384    * 实际上就是路径中的最后一个路径分隔符后的部分。
385    * @param fileName 文件名
386    * @return 文件名中的名字部分
387    * @since  1.0
388    */
389   public static String getNamePart(String fileName) {
390     int point = getPathLsatIndex(fileName);
391     int length = fileName.length();
392     if (point == -1) {
393       return fileName;
394     }
395     else if (point == length - 1) {
396       int secondPoint = getPathLsatIndex(fileName, point - 1);
397       if (secondPoint == -1) {
398         if (length == 1) {
399           return fileName;
400         }
401         else {
402           return fileName.substring(0, point);
403         }
404       }
405       else {
406         return fileName.substring(secondPoint + 1, point);
407       }
408     }
409     else {
410       return fileName.substring(point + 1);
411     }
412   }
413 
414   /**
415    * 得到文件名中的父路径部分。
416    * 对两种路径分隔符都有效。
417    * 不存在时返回""。
418    * 如果文件名是以路径分隔符结尾的则不考虑该分隔符,例如"/path/"返回""。
419    * @param fileName 文件名
420    * @return 父路径,不存在或者已经是父目录时返回""
421    * @since  1.0
422    */
423   public static String getPathPart(String fileName) {
424     int point = getPathLsatIndex(fileName);
425     int length = fileName.length();
426     if (point == -1) {
427       return "";
428     }
429     else if (point == length - 1) {
430       int secondPoint = getPathLsatIndex(fileName, point - 1);
431       if (secondPoint == -1) {
432         return "";
433       }
434       else {
435         return fileName.substring(0, secondPoint);
436       }
437     }
438     else {
439       return fileName.substring(0, point);
440     }
441   }
442 
443   /**
444    * 得到路径分隔符在文件路径中首次出现的位置。
445    * 对于DOS或者UNIX风格的分隔符都可以。
446    * @param fileName 文件路径
447    * @return 路径分隔符在路径中首次出现的位置,没有出现时返回-1。
448    * @since  1.0
449    */
450   public static int getPathIndex(String fileName) {
451     int point = fileName.indexOf(‘/‘);
452     if (point == -1) {
453       point = fileName.indexOf(‘\\‘);
454     }
455     return point;
456   }
457 
458   /**
459    * 得到路径分隔符在文件路径中指定位置后首次出现的位置。
460    * 对于DOS或者UNIX风格的分隔符都可以。
461    * @param fileName 文件路径
462    * @param fromIndex 开始查找的位置
463    * @return 路径分隔符在路径中指定位置后首次出现的位置,没有出现时返回-1。
464    * @since  1.0
465    */
466   public static int getPathIndex(String fileName, int fromIndex) {
467     int point = fileName.indexOf(‘/‘, fromIndex);
468     if (point == -1) {
469       point = fileName.indexOf(‘\\‘, fromIndex);
470     }
471     return point;
472   }
473 
474   /**
475    * 得到路径分隔符在文件路径中最后出现的位置。
476    * 对于DOS或者UNIX风格的分隔符都可以。
477    * @param fileName 文件路径
478    * @return 路径分隔符在路径中最后出现的位置,没有出现时返回-1。
479    * @since  1.0
480    */
481   public static int getPathLsatIndex(String fileName) {
482     int point = fileName.lastIndexOf(‘/‘);
483     if (point == -1) {
484       point = fileName.lastIndexOf(‘\\‘);
485     }
486     return point;
487   }
488 
489   /**
490    * 得到路径分隔符在文件路径中指定位置前最后出现的位置。
491    * 对于DOS或者UNIX风格的分隔符都可以。
492    * @param fileName 文件路径
493    * @param fromIndex 开始查找的位置
494    * @return 路径分隔符在路径中指定位置前最后出现的位置,没有出现时返回-1。
495    * @since  1.0
496    */
497   public static int getPathLsatIndex(String fileName, int fromIndex) {
498     int point = fileName.lastIndexOf(‘/‘, fromIndex);
499     if (point == -1) {
500       point = fileName.lastIndexOf(‘\\‘, fromIndex);
501     }
502     return point;
503   }
504 
505   /**
506    * 将文件名中的类型部分去掉。
507    * @param filename 文件名
508    * @return 去掉类型部分的结果
509    * @since  1.0
510    */
511   public static String trimType(String filename) {
512     int index = filename.lastIndexOf(".");
513     if (index != -1) {
514       return filename.substring(0, index);
515     }
516     else {
517       return filename;
518     }
519   }
520   /**
521    * 得到相对路径。
522    * 文件名不是目录名的子节点时返回文件名。
523    * @param pathName 目录名
524    * @param fileName 文件名
525    * @return 得到文件名相对于目录名的相对路径,目录下不存在该文件时返回文件名
526    * @since  1.0
527    */
528   public static String getSubpath(String pathName,String fileName) {
529     int index = fileName.indexOf(pathName);
530     if (index != -1) {
531       return fileName.substring(index + pathName.length() + 1);
532     }
533     else {
534       return fileName;
535     }
536   }
537 
538   /**
539    * 检查给定目录的存在性
540    * 保证指定的路径可用,如果指定的路径不存在,那么建立该路径,可以为多级路径
541    * @param path
542    * @return 真假值
543    * @since  1.0
544    */
545    public static final boolean pathValidate(String path)
546    {
547      //String path="d:/web/www/sub";
548      //System.out.println(path);
549      //path = getUNIXfilePath(path);
550 
551      //path = ereg_replace("^\\/+", "", path);
552      //path = ereg_replace("\\/+$", "", path);
553      String[] arraypath = path.split("/");
554      String tmppath = "";
555      for (int i = 0; i < arraypath.length; i++)
556      {
557        tmppath += "/" + arraypath[i];
558        File d = new File(tmppath.substring(1));
559        if (!d.exists()) { //检查Sub目录是否存在
560            System.out.println(tmppath.substring(1));
561          if (!d.mkdir())
562          {
563            return false;
564          }
565        }
566      }
567      return true;
568    }
569 
570    /**
571     * 读取文件的内容
572     * 读取指定文件的内容
573     * @param path 为要读取文件的绝对路径
574     * @return 以行读取文件后的内容。
575     * @since  1.0
576     */
577    public static final String getFileContent(String path) throws IOException
578    {
579      String filecontent = "";
580      try {
581        File f = new File(path);
582        if (f.exists()) {
583          FileReader fr = new FileReader(path);
584          BufferedReader br = new BufferedReader(fr); //建立BufferedReader对象,并实例化为br
585          String line = br.readLine(); //从文件读取一行字符串
586          //判断读取到的字符串是否不为空
587          while (line != null) {
588            filecontent += line + "\n";
589            line = br.readLine(); //从文件中继续读取一行数据
590          }
591          br.close(); //关闭BufferedReader对象
592          fr.close(); //关闭文件
593        }
594 
595      }
596      catch (IOException e) {
597        throw e;
598      }
599      return filecontent;
600    }
601 
602    /**
603     * 根据内容生成文件
604     * @param path要生成文件的绝对路径,
605     * @param 文件的内容。
606     * @return 真假值
607     * @since  1.0
608     */
609    public static final boolean genModuleTpl(String path, String modulecontent)  throws IOException
610    {
611 
612      path = getUNIXfilePath(path);
613      String[] patharray = path.split("\\/");
614      String modulepath = "";
615      for (int i = 0; i < patharray.length - 1; i++) {
616        modulepath += "/" + patharray[i];
617      }
618      File d = new File(modulepath.substring(1));
619      if (!d.exists()) {
620        if (!pathValidate(modulepath.substring(1))) {
621          return false;
622        }
623      }
624      try {
625        FileWriter fw = new FileWriter(path); //建立FileWriter对象,并实例化fw
626        //将字符串写入文件
627        fw.write(modulecontent);
628        fw.close();
629      }
630      catch (IOException e) {
631        throw e;
632      }
633      return true;
634    }
635 
636    /**
637     * 获取图片文件的扩展名(发布系统专用)
638     * @param picname 为图片名称加上前面的路径不包括扩展名
639     * @return 图片的扩展名
640     * @since  1.0
641     */
642    public static final String getPicExtendName(String pic_path)
643    {
644      pic_path = getUNIXfilePath(pic_path);
645      String pic_extend = "";
646      if (isFileExist(pic_path + ".gif"))
647      {
648        pic_extend = ".gif";
649      }
650      if (isFileExist(pic_path + ".jpeg"))
651      {
652        pic_extend = ".jpeg";
653      }
654      if (isFileExist(pic_path + ".jpg"))
655      {
656        pic_extend = ".jpg";
657      }
658      if (isFileExist(pic_path + ".png"))
659      {
660        pic_extend = ".png";
661      }
662      return pic_extend; //返回图片扩展名
663    }
664    //拷贝文件
665    public static final boolean CopyFile(File in, File out) throws Exception {
666        try {
667            FileInputStream fis = new FileInputStream(in);
668            FileOutputStream fos = new FileOutputStream(out);
669            byte[] buf = new byte[1024];
670            int i = 0;
671            while ((i = fis.read(buf)) != -1) {
672                fos.write(buf, 0, i);
673            }
674            fis.close();
675            fos.close();
676            return true;
677        } catch (IOException ie) {
678            ie.printStackTrace();
679            return false;
680        }
681    }
682    //拷贝文件
683    public static final boolean CopyFile(String infile, String outfile) throws Exception {
684        try {
685            File in = new File(infile);
686            File out = new File(outfile);
687            return CopyFile(in, out);
688        } catch (IOException ie) {
689            ie.printStackTrace();
690            return false;
691        }
692 
693    }
694    /**
695     * 计算图片数量
696     * @param id
697     * @param dtime
698     * @return
699     */
700    public static final int countPics(String id,String dtime,String extensions){
701        int counts = 0; 
702        
703        MyFileFilter mfilter = new MyFileFilter(extensions.split(","));
704        PropsUtil pu = new PropsUtil();
705        String PICROOT = pu.readSingleProps("DestinationsPICROOT").trim();
706        String path = PICROOT + "/"+dtime.substring(0, 10) + "/";
707        File lfile = new File(path);
708        String filename;
709        if(lfile.isDirectory()){
710            File[] files = lfile.listFiles(mfilter);
711            for(int i=0;i<files.length;i++){
712                filename = files[i].getName();
713                if((filename.indexOf(id + "_")==0)&&(filename.indexOf("_small")>-1))
714                    counts ++;
715            }
716            files = null;
717        }
718        filename = null;
719        lfile = null;
720        pu = null;
721        mfilter = null;
722            
723        return counts;
724    }
725 
726 }

 

FileUtil

标签:des   style   blog   io   color   ar   os   使用   java   

原文地址:http://www.cnblogs.com/leorain/p/4093626.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!