文件處理

          package nl.enovation.ems.transferlink.client.util;

          import java.io.File;
          import java.io.FileInputStream;
          import java.io.FileOutputStream;
          import java.io.IOException;
          import java.io.InputStream;
          import java.io.RandomAccessFile;
          import java.nio.ByteBuffer;
          import java.nio.MappedByteBuffer;
          import java.nio.channels.Channels;
          import java.nio.channels.FileChannel;
          import java.nio.channels.ReadableByteChannel;
          import java.nio.channels.WritableByteChannel;
          import java.util.ArrayList;
          import java.util.Collection;
          import java.util.Enumeration;
          import java.util.zip.ZipEntry;
          import java.util.zip.ZipFile;
          import java.util.zip.ZipOutputStream;

          public class FileUtil {


           public static void moveFile(File source, String path) throws IOException {
            if(!source.renameTo(new File(path, source.getName()))){
             throw new IOException(
               "Can't move file "
               + source.getName()
               + " to "
               + path);
            }
           }
           
           public static File moveFile(File source, File path) throws IOException {
            File newFile = new File(path, source.getName());
            if(!source.renameTo(newFile)){
             throw new IOException(
               "Can't move file "
               + source.getName()
               + " to "
               + path);
            }
            return newFile;
           }
           
           public static void moveFile(File source, File path, boolean uniqueFileName) throws IOException {
            String fileName = source.getName();
            File file = new File(path, fileName);
            int count = 1;
            while(true) {
             if(file.exists()) {
              String newFileName = null;
              int idx = fileName.lastIndexOf(".");
              if(idx > 0) {
               newFileName = fileName.substring(0, idx) + "." + count + fileName.substring(idx); 
              } else {
               newFileName = fileName + "." + count;
              }
              file = new File(path, newFileName);
              count++;
             } else {
              break;
             }
            }
            if(!source.renameTo(file)){
             //try {
             // copyFile(source, file);
             // deleteFile(source);
             //}
             //catch (IOException e)
             //{
              throw new IOException(
                "Can't move file "
                + source.getName() //+ " (" + source.getAbsolutePath() + ")"
                + " to "
                + path);
               //+"("+e.getMessage()+")");
               // + " (" + file.getAbsolutePath() + ")");
             //}
            }
           }
           
           public static void moveFiles(File sourceDir, File destDir) throws IOException {
            java.io.File[] list=sourceDir.listFiles();
            for (int i = 0; i < list.length; i++) {
             if (!list[i].isDirectory()) {
              if(!list[i].renameTo(new File(destDir, list[i].getName()))) {
               throw new IOException(
                 "Can't move file "
                 + list[i].getName()
                 + " to "
                 + destDir.getAbsolutePath());
              }
             }
            }
           }
           
           /**
            * Copy a File (source) to a File (destination)
            * @param source
            * @param dest
            * @throws IOException
            */
           public static void copyFile(File source, File dest) throws IOException {
                FileChannel in = null, out = null;
                try {         
                     in = new FileInputStream(source).getChannel();
                     out = new FileOutputStream(dest).getChannel();

                     long size = in.size();
                     MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size);
                     out.write(buf);

                } finally {
                     if (in != null)     
                      in.close();
                     if (out != null)    
                      out.close();
                }
           }
           
           /**
            * Write an input stream to a file.
            * @param source
            * @param dest
            * @param size
            * @throws IOException
            */
           public static int writeFile(InputStream source, File dest, long buffer) throws IOException {
            int bytesWrote = 0;
            FileChannel out = null;
            ReadableByteChannel in = null;
            ByteBuffer data = ByteBuffer.allocate((int) buffer);
            try {
             in = Channels.newChannel(source);
             out = new FileOutputStream(dest).getChannel();
             
             int read = in.read(data);
             while(read > 0) {
              bytesWrote += read;
              data.flip();
              out.write(data);
              data.clear();
              read = in.read(data);
             }

            } finally {
             if(out != null)
              out.close();
             if(in != null)
              in.close();
            }
            return bytesWrote;
           }
           
           public static void delete(java.io.File path) throws IOException {
            if (path.isDirectory()) {
             deleteDirectory(path);
            } else {
             deleteFile(path);
            }
           }
           
           protected static void deleteDirectory(java.io.File path) throws IOException {
            java.io.File[] list = path.listFiles();
            for (int i = 0; i < list.length; i++) {
             if (list[i].isDirectory()) {
              deleteDirectory(list[i]);
              if (!list[i].delete()) {
               throw new IOException("Can't delete directory '"+list[i]+"'.");
              }
             } else {
              deleteFile(list[i]);
             }
            }
           }
           
           protected static void deleteFile(java.io.File path) throws IOException {
            if (!path.delete()) {
             throw new IOException("Can't delete file '"+path+"'.");
            }
           }
           
           // TODO optimize ... read and write with buffers?!
           //@SuppressWarnings("unchecked")
           public static Collection splitFile(File file, int splitlen, File tmpDir) throws IOException
           {
            long leng = 0;
            int count = 1, read = 0;
            byte [] buffer = new byte[8196];
            
            String fileName  = file.getName();
            Collection files = new ArrayList();  
            RandomAccessFile infile = new RandomAccessFile(file, "r");
            read = infile.read(buffer);
            while(read != -1)
            {
             file = new File(tmpDir, fileName + ".lms.sp" + count);
             RandomAccessFile outfile = new RandomAccessFile(file, "rw");
             while( read != -1 && leng < splitlen)
             {
              outfile.write(buffer, 0, read);
              leng += read;
              read = infile.read(buffer);
             }
             leng = 0;
             outfile.close();
             file.deleteOnExit();
             files.add(file);
             count++;
            }
            return files;
           }
           
           public static File joinFile(String fileName, File tmpDir) throws IOException
           {
            int count = 1, read = 0;
            byte [] buffer = new byte[8196];
            
            File destFile = new File(tmpDir, fileName);
            RandomAccessFile outfile = new RandomAccessFile(destFile, "rw");
            while(true)
            {
             File readFile = new File(tmpDir, fileName + ".lms.sp" + count);
             if (readFile.exists())
             {
              RandomAccessFile infile = new RandomAccessFile(readFile, "r");
              read = infile.read(buffer);
              while(read != -1)
              {
               outfile.write(buffer, 0, read);
               read = infile.read(buffer);
              }
              infile.close();
              readFile.delete();
              count++;
             }
             else
             {
              break;
             }
            }
            outfile.close();
            return destFile;
           }
           
           public static boolean isComplete(String fileName, File dir, int parts) {
            int counter = 1;
            int matched = 0;
            File[] list = dir.listFiles();
            for (int i = 0; i < list.length; i++) {
             if (!list[i].isDirectory()) {
              String f = list[i].getName();
              String f2 = fileName + ".lms.sp";
              if(f.startsWith(f2)) {
               matched++;
              }
              counter++;
             }
            }
            if(matched == parts) {
             return true;
            } else {
             return false;
            }
            
           }
           
           public static File zipFile(File file, File dir) throws IOException {
            WritableByteChannel out = null;
            ReadableByteChannel in = null;
            FileInputStream source = new FileInputStream(file);
            File dest = new File(dir, file.getName() + ".zip");
            ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(dest));
            dest.deleteOnExit();
            int buffer = 4096;
            ByteBuffer data = ByteBuffer.allocate(buffer);
            try {
             zos.putNextEntry(new ZipEntry(file.getName()));

             in = Channels.newChannel(source);
             out = Channels.newChannel(zos);
             
             int read = in.read(data);
             while(read > 0) {
              data.flip();
              out.write(data);
              data.clear();
              read = in.read(data);
             }
             
             zos.closeEntry();
            } finally {
             if(zos != null) {
              zos.finish();
             }
             if(out != null)
              out.close();
             if(in != null)
              in.close();
            }
            return dest;
           }
           
           public static File unzipFile(File file, File dir) throws IOException {
            WritableByteChannel out = null;
            ReadableByteChannel in = null;
            ZipEntry entry = null;
            ZipFile zipFile = null;
            int buffer = 4096;
            ByteBuffer data = ByteBuffer.allocate(buffer);
            File unzippedFile = null;
            try {
             zipFile = new ZipFile(file, ZipFile.OPEN_READ);
             Enumeration zipFileEntries = zipFile.entries();
                
             // Process each entry
             if (zipFileEntries.hasMoreElements()) {
              // grab a zip file entry
              entry = (ZipEntry) zipFileEntries.nextElement();
              String currentEntry = entry.getName();
              InputStream input = zipFile.getInputStream(entry);
              unzippedFile = new File(dir, currentEntry);
              FileOutputStream output = new FileOutputStream(unzippedFile);
              
              in = Channels.newChannel(input);
              out = Channels.newChannel(output);

              int read = in.read(data);
              while(read > 0) {
               data.flip();
               out.write(data);
               data.clear();
               read = in.read(data);
              }
             }
            } finally {
             if(file != null)
              file.delete();
             if(zipFile != null)
              zipFile.close();
             if(out != null)
              out.close();
             if(in != null)
              in.close();
            }
            return unzippedFile;
           }
          }


          不過最好使用Apache Common 的IO組件。
          里面有個(gè)FileUtils,提供了很多很好的方法。
          可以參考:
           

          http://commons.apache.org/io/apidocs/index.html

          posted on 2008-01-21 17:44 劉錚 閱讀(337) 評(píng)論(0)  編輯  收藏 所屬分類: JAVA General

          <2025年5月>
          27282930123
          45678910
          11121314151617
          18192021222324
          25262728293031
          1234567

          導(dǎo)航

          統(tǒng)計(jì)

          留言簿(1)

          文章分類(141)

          文章檔案(147)

          搜索

          最新評(píng)論

          主站蜘蛛池模板: 葫芦岛市| 绵竹市| 屯留县| 常熟市| 邻水| 庄浪县| 满城县| 黎城县| 牡丹江市| 盘锦市| 北票市| 温宿县| 大埔县| 奈曼旗| 灵武市| 宜兴市| 渭源县| 阳朔县| 金平| 新沂市| 西昌市| 沧源| 信丰县| 平塘县| 城市| 松溪县| 德安县| 常宁市| 汕尾市| 永昌县| 盖州市| 女性| 左云县| 绍兴市| 桐柏县| 宜黄县| 广宗县| 滨海县| 宝清县| 新河县| 沅陵县|