zoukankan      html  css  js  c++  java
  • Java中创建操作文件和文件夹的工具类

    Java中创建操作文件和文件夹的工具类

    FileUtils.java

      1 import java.io.BufferedInputStream;
      2 import java.io.BufferedOutputStream;
      3 import java.io.File;
      4 import java.io.FileInputStream;
      5 import java.io.FileNotFoundException;
      6 import java.io.FileOutputStream;
      7 import java.io.IOException;
      8 import java.io.InputStream;
      9 import java.net.MalformedURLException;
     10 import java.net.URL;
     11 import java.net.URLConnection;
     12 import java.nio.channels.FileChannel;
     13 
     14 import org.junit.Test;
     15 
     16 /**
     17  * 
     18  * @version 创建时间:2010-6-8 下午02:58:29
     19  * @Description
     20  */
     21 
     22 public class FileUtils {
     23     /**
     24      * 获取文件编码格式
     25      * @param fileName
     26      * @return
     27      * @throws Exception
     28      */
     29     public static String getFileEncoding(String fileName) throws Exception {
     30         BufferedInputStream bin = new BufferedInputStream(new FileInputStream(fileName));
     31         int p = (bin.read() << 8) + bin.read();
     32         String code = null;
     33         switch (p) {
     34         case 0xefbb:
     35             code = "UTF-8";
     36             break;
     37         case 0xfffe:
     38             code = "Unicode";
     39             break;
     40         case 0xfeff:
     41             code = "UTF-16BE";
     42             break;
     43         default:
     44             code = "GBK";
     45         }
     46 
     47         return code;
     48     }
     49     
     50     /**
     51      * 拷贝文件到指定的路径 (使用了自定义的CopyFileUtil工具类)
     52      * @param fileURL
     53      * @param targetFile
     54      */
     55     public void copy(String fileURL ,String targetFile){
     56         URLConnection urlconn = null ;
     57         try {
     58             URL url = new URL(fileURL);
     59             urlconn = url.openConnection();
     60             InputStream in = urlconn.getInputStream();
     61 
     62             File newfile = new File(targetFile);        
     63             FileOutputStream fos = new FileOutputStream(newfile);
     64             CopyFileUtil.copy(in, fos);//使用了自定义的FileUtil工具类
     65         } catch (MalformedURLException e) {
     66             e.printStackTrace();
     67         } catch (IOException e) {
     68             e.printStackTrace();
     69         } 
     70     }
     71     
     72     
     73     /**
     74      * 复制文件
     75      * @param sourceFile
     76      * @param targetFile
     77      * @throws IOException
     78      */
     79     public static void copyFile(File sourceFile, File targetFile)
     80             throws IOException {
     81         // 新建文件输入流并对它进行缓冲
     82         FileInputStream input = new FileInputStream(sourceFile);
     83         BufferedInputStream inBuff = new BufferedInputStream(input);
     84         // 新建文件输出流并对它进行缓冲
     85         FileOutputStream output = new FileOutputStream(targetFile);
     86         BufferedOutputStream outBuff = new BufferedOutputStream(output);
     87         // 缓冲数组
     88         byte[] b = new byte[1024 * 5];
     89         int len;
     90         while ((len = inBuff.read(b)) != -1) {
     91             outBuff.write(b, 0, len);
     92         }
     93         // 刷新此缓冲的输出流
     94         outBuff.flush();
     95         // 关闭流
     96         inBuff.close();
     97         outBuff.close();
     98         output.close();
     99         input.close();
    100     }
    101 
    102     /**
    103      * 复制文件夹
    104      * @param sourceDir
    105      * @param targetDir
    106      * @throws IOException
    107      */
    108     public static void copyDirectiory(String sourceDir, String targetDir)
    109             throws IOException {
    110         // 新建目标目录
    111         (new File(targetDir)).mkdirs();
    112         // 获取源文件夹当前下的文件或目录
    113         File[] file = (new File(sourceDir)).listFiles();
    114         for (int i = 0; i < file.length; i++) {
    115             if (file[i].isFile()) {
    116                 // 源文件
    117                 File sourceFile = file[i];
    118                 // 目标文件
    119                 File targetFile = new File(new File(targetDir)
    120                         .getAbsolutePath()
    121                         + File.separator + file[i].getName());
    122                 if (sourceFile.getName().indexOf(".vax") < 0)
    123                     copyFile(sourceFile, targetFile);
    124             }
    125             if (file[i].isDirectory()) {
    126                 // 准备复制的源文件夹
    127                 String dir1 = sourceDir + "/" + file[i].getName();
    128                 // 准备复制的目标文件夹
    129                 String dir2 = targetDir + "/" + file[i].getName();
    130                 copyDirectiory(dir1, dir2);
    131             }
    132         }
    133     }
    134     
    135     /**
    136      * 得到文件的扩展名
    137      * @param f
    138      * @return
    139      */
    140     public static String getFileExtension(File f) {
    141         if (f != null) {
    142             String filename = f.getName();
    143             int i = filename.lastIndexOf('.');
    144             if (i > 0 && i < filename.length() - 1) {
    145                 return filename.substring(i + 1).toLowerCase();
    146             }
    147         }
    148         return null;
    149     }
    150     /**
    151      * 得到文件名(排除文件扩展名)
    152      * @param f
    153      * @return
    154      */
    155     public static String getFileNameWithoutExt(File f) {
    156         if (f != null) {
    157             String filename = f.getName();
    158             int i = filename.lastIndexOf('.');
    159             if (i > 0 && i < filename.length() - 1) {
    160                 return filename.substring(0, i);
    161             }
    162         }
    163         return null;
    164     }
    165     
    166     /**
    167      * 改变文件的扩展名
    168      * @param fileNM
    169      * @param ext
    170      * @return
    171      */
    172     public static String changeFileExt(String fileNM, String ext) {
    173         int i = fileNM.lastIndexOf('.');
    174         if (i >= 0)
    175             return (fileNM.substring(0, i) + ext);
    176         else
    177             return fileNM;
    178     }
    179     
    180     /**
    181      * 得到文件的全路径
    182      * @param filePath
    183      * @return
    184      */
    185     public static String getFileNameWithFullPath(String filePath) {
    186         int i = filePath.lastIndexOf('/');
    187         int j = filePath.lastIndexOf("\");
    188         int k;
    189         if (i >= j) {
    190             k = i;
    191         } else {
    192             k = j;
    193         }
    194         int n = filePath.lastIndexOf('.');
    195         if (n > 0) {
    196             return filePath.substring(k + 1, n);
    197         } else {
    198             return filePath.substring(k + 1);
    199         }
    200     }
    201 
    202 
    203 
    204     /**
    205      * 判断目录是否存在
    206      * @param strDir
    207      * @return
    208      */
    209     public static boolean existsDirectory(String strDir) {
    210         File file = new File(strDir);
    211         return file.exists() && file.isDirectory();
    212     }
    213     
    214     /**
    215      * 判断文件是否存在
    216      * @param strDir
    217      * @return
    218      */
    219     public static boolean existsFile(String strDir) {
    220         File file = new File(strDir);
    221         return file.exists();
    222     }
    223     
    224     /**
    225      * 强制创建目录
    226      * @param strDir
    227      * @return
    228      */
    229     public static boolean forceDirectory(String strDir) {
    230         File file = new File(strDir);
    231         file.mkdirs();
    232         return existsDirectory(strDir);
    233     }
    234     
    235     /**
    236      * 得到文件的大小
    237      * @param fileName
    238      * @return
    239      */
    240     public static int getFileSize(String fileName){
    241         
    242         File file = new File(fileName);
    243         FileInputStream fis = null;
    244         int size = 0 ;
    245         try {
    246             fis = new FileInputStream(file);
    247             size = fis.available();
    248         }catch (Exception e) {
    249             e.printStackTrace();
    250         }
    251         return size ;
    252     }
    253 
    254 }

    CpoyFileUtil.java(主要都是文件复制相关的方法)

      1 import java.io.BufferedInputStream;
      2 import java.io.BufferedOutputStream;
      3 import java.io.ByteArrayInputStream;
      4 import java.io.ByteArrayOutputStream;
      5 import java.io.File;
      6 import java.io.FileInputStream;
      7 import java.io.FileNotFoundException;
      8 import java.io.FileOutputStream;
      9 import java.io.IOException;
     10 import java.io.InputStream;
     11 import java.io.OutputStream;
     12 import java.io.Reader;
     13 import java.io.StringWriter;
     14 import java.io.Writer;
     15 import java.net.MalformedURLException;
     16 import java.net.URL;
     17 import java.net.URLConnection;
     18 import java.text.CollationKey;
     19 import java.text.Collator;
     20 import java.text.RuleBasedCollator;
     21 import java.util.ArrayList;
     22 import java.util.Arrays;
     23 import java.util.Comparator;
     24 import java.util.List;
     25 
     26 import org.apache.log4j.Logger;
     27 
     28 /**
     29  * Simple utility methods for file and stream copying.
     30  * All copy methods use a block size of 4096 bytes,
     31  * and close all affected streams when done.
     32  *
     33  * <p>Mainly for use within the framework,
     34  * but also useful for application code.
     35  *
     36  * @author John Summer
     37  */
     38 public abstract class CopyFileUtil {
     39 
     40     private static final Logger logger = Logger.getLogger(FileUtil.class);
     41 
     42     public static final int BUFFER_SIZE = 4096;
     43 
     44     /**
     45      * judge whether it's exist
     46      * @param strFilePath String
     47      * @return boolean
     48      */
     49     public static boolean isExist(String filepath) {
     50         File file = new File(filepath);
     51         return file.exists();
     52     }
     53     
     54     public static void copy(String fileURL ,String targetFile){
     55         URLConnection urlconn = null ;
     56         try {
     57             URL url = new URL(fileURL);
     58             urlconn = url.openConnection();
     59             InputStream in = urlconn.getInputStream();
     60 
     61             File newfile = new File(targetFile);        
     62             FileOutputStream fos = new FileOutputStream(newfile);
     63             FileUtil.copy(in, fos);                
     64         } catch (MalformedURLException e) {
     65             e.printStackTrace();
     66         } catch (IOException e) {
     67             e.printStackTrace();
     68         } 
     69     }
     70     
     71     /**
     72      * Copy the contents of the given input File to the given output File.
     73      * @param in the file to copy from
     74      * @param out the file to copy to
     75      * @return the number of bytes copied
     76      * @throws IOException in case of I/O errors
     77      */
     78     public static int copy(File in, File out) throws IOException {
     79         Assert.notNull(in, "No input File specified");
     80         Assert.notNull(out, "No output File specified");
     81         return copy(new BufferedInputStream(new FileInputStream(in)),
     82             new BufferedOutputStream(new FileOutputStream(out)));
     83     }
     84 
     85     /**
     86      * Copy the contents of the given byte array to the given output File.
     87      * @param in the byte array to copy from
     88      * @param out the file to copy to
     89      * @throws IOException in case of I/O errors
     90      */
     91     public static void copy(byte[] in, File out) throws IOException {
     92         Assert.notNull(in, "No input byte array specified");
     93         Assert.notNull(out, "No output File specified");
     94         ByteArrayInputStream inStream = new ByteArrayInputStream(in);
     95         OutputStream outStream = new BufferedOutputStream(new FileOutputStream(out));
     96         copy(inStream, outStream);
     97     }
     98 
     99     /**
    100      * Copy the contents of the given input File into a new byte array.
    101      * @param in the file to copy from
    102      * @return the new byte array that has been copied to
    103      * @throws IOException in case of I/O errors
    104      */
    105     public static byte[] copyToByteArray(File in) throws IOException {
    106         Assert.notNull(in, "No input File specified");
    107         return copyToByteArray(new BufferedInputStream(new FileInputStream(in)));
    108     }
    109 
    110     /**
    111      * Copy the contents of the given InputStream to the given OutputStream.
    112      * Closes both streams when done.
    113      * @param in the stream to copy from
    114      * @param out the stream to copy to
    115      * @return the number of bytes copied
    116      * @throws IOException in case of I/O errors
    117      */
    118     public static int copy(InputStream in, OutputStream out) throws IOException {
    119         Assert.notNull(in, "No InputStream specified");
    120         Assert.notNull(out, "No OutputStream specified");
    121         try {
    122             int byteCount = 0;
    123             byte[] buffer = new byte[BUFFER_SIZE];
    124             int bytesRead = -1;
    125             while ((bytesRead = in.read(buffer)) != -1) {
    126                 out.write(buffer, 0, bytesRead);
    127                 byteCount += bytesRead;
    128             }
    129             out.flush();
    130             return byteCount;
    131         }
    132         finally {
    133             try {
    134                 in.close();
    135             }
    136             catch (IOException ex) {
    137                 logger.warn("Could not close InputStream", ex);
    138             }
    139             try {
    140                 out.close();
    141             }
    142             catch (IOException ex) {
    143                 logger.warn("Could not close OutputStream", ex);
    144             }
    145         }
    146     }
    147 
    148     /**
    149      * Copy the contents of the given byte array to the given OutputStream.
    150      * Closes the stream when done.
    151      * @param in the byte array to copy from
    152      * @param out the OutputStream to copy to
    153      * @throws IOException in case of I/O errors
    154      */
    155     public static void copy(byte[] in, OutputStream out) throws IOException {
    156         Assert.notNull(in, "No input byte array specified");
    157         Assert.notNull(out, "No OutputStream specified");
    158         try {
    159             out.write(in);
    160         }
    161         finally {
    162             try {
    163                 out.close();
    164             }
    165             catch (IOException ex) {
    166                 logger.warn("Could not close OutputStream", ex);
    167             }
    168         }
    169     }
    170 
    171     /**
    172      * Copy the contents of the given InputStream into a new byte array.
    173      * Closes the stream when done.
    174      * @param in the stream to copy from
    175      * @return the new byte array that has been copied to
    176      * @throws IOException in case of I/O errors
    177      */
    178     public static byte[] copyToByteArray(InputStream in) throws IOException {
    179         ByteArrayOutputStream out = new ByteArrayOutputStream(BUFFER_SIZE);
    180         copy(in, out);
    181         return out.toByteArray();
    182     }
    183 
    184     /**
    185      * Copy the contents of the given Reader to the given Writer.
    186      * Closes both when done.
    187      * @param in the Reader to copy from
    188      * @param out the Writer to copy to
    189      * @return the number of characters copied
    190      * @throws IOException in case of I/O errors
    191      */
    192     public static int copy(Reader in, Writer out) throws IOException {
    193         Assert.notNull(in, "No Reader specified");
    194         Assert.notNull(out, "No Writer specified");
    195         try {
    196             int byteCount = 0;
    197             char[] buffer = new char[BUFFER_SIZE];
    198             int bytesRead = -1;
    199             while ((bytesRead = in.read(buffer)) != -1) {
    200                 out.write(buffer, 0, bytesRead);
    201                 byteCount += bytesRead;
    202             }
    203             out.flush();
    204             return byteCount;
    205         }
    206         finally {
    207             try {
    208                 in.close();
    209             }
    210             catch (IOException ex) {
    211                 logger.warn("Could not close Reader", ex);
    212             }
    213             try {
    214                 out.close();
    215             }
    216             catch (IOException ex) {
    217                 logger.warn("Could not close Writer", ex);
    218             }
    219         }
    220     }
    221 
    222     /**
    223      * Copy the contents of the given String to the given output Writer.
    224      * Closes the write when done.
    225      * @param in the String to copy from
    226      * @param out the Writer to copy to
    227      * @throws IOException in case of I/O errors
    228      */
    229     public static void copy(String in, Writer out) throws IOException {
    230         Assert.notNull(in, "No input String specified");
    231         Assert.notNull(out, "No Writer specified");
    232         try {
    233             out.write(in);
    234         }
    235         finally {
    236             try {
    237                 out.close();
    238             }
    239             catch (IOException ex) {
    240                 logger.warn("Could not close Writer", ex);
    241             }
    242         }
    243     }
    244 
    245     /**
    246      * Copy the contents of the given Reader into a String.
    247      * Closes the reader when done.
    248      * @param in the reader to copy from
    249      * @return the String that has been copied to
    250      * @throws IOException in case of I/O errors
    251      */
    252     public static String copyToString(Reader in) throws IOException {
    253         StringWriter out = new StringWriter();
    254         copy(in, out);
    255         return out.toString();
    256     }
    257 
    258 }
  • 相关阅读:
    POJ 2388(排序)
    优先队列(堆实现)
    POJ 3322(广搜)
    POJ 1190(深搜)
    POJ 1456(贪心)
    poj 2524 (并查集)
    poj 1611(并查集)
    poj 1521
    poj 1220(短除法)
    css 如何实现图片等比例缩放
  • 原文地址:https://www.cnblogs.com/DreamDrive/p/5762588.html
Copyright © 2011-2022 走看看