文件处理

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组件。
里面有个FileUtils,提供了很多很好的方法。
可以参考:
 

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

posted on 2008-01-21 17:44 刘铮 阅读(309) 评论(0)  编辑  收藏 所属分类: JAVA General


只有注册用户登录后才能发表评论。


网站导航:
 
<2024年5月>
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678

导航

统计

留言簿(1)

文章分类(141)

文章档案(147)

搜索

最新评论