Thứ Hai, 5 tháng 8, 2013

Coppy and Remove file trong Java

Trong lập trình nhiều khi chúng ta phải thao tác với file, ngoài việc đọc và ghi, thì còn phải coppy và delete file, delete file theo .extend
Class util  hỗ trợ mục đích của ta:
FileUtil.java
package vn.ds.util;

import java.io.*;

public class FileUtil {

 /**
  * Coppy data từ một file nguồn vào file đích
  */
 public static void copyFile(File source, File dest) throws IOException {

  if (!dest.exists()) {
   dest.createNewFile();
  }
  InputStream in = null;
  OutputStream out = null;
  try {
   in = new FileInputStream(source);
   out = new FileOutputStream(dest);
   // Transfer bytes from in to out
   byte[] buf = new byte[1024];
   int len;
   while ((len = in.read(buf)) > 0) {
    out.write(buf, 0, len);
   }

  } catch (Exception ex) {
   System.out.println("error");
  } finally {
   in.close();
   out.close();
  }
 }

 /**
  * Coppy tất cả các file trong thư mục nguồn đến thư mục đích
  */
 public static void copyDirectory(File sourceDir, File destDir)
   throws IOException {
  if (!destDir.exists()) {
   destDir.setWritable(true);
   destDir.mkdirs();
  } else {
   destDir.setWritable(true);
  }
  File[] children = sourceDir.listFiles();
  for (File sourceChild : children) {
   String name = sourceChild.getName();
   File destChild = new File(destDir, name);
   if (sourceChild.isDirectory()) {
    copyDirectory(sourceChild, destChild);
   } else {
    copyFile(sourceChild, destChild);
   }
  }
 }

 /**
  * xoá một thư mục (bao gồm các file trong thư mục đó)
  */
 public static boolean delete(File resource) throws IOException {
  if (resource.isDirectory()) {
   File[] childFiles = resource.listFiles();
   for (File child : childFiles) {
    delete(child);
   }
  }
  return resource.delete();
 }

 /**
  * xoá các file trong một thư mục có đuôi mở rộng là một parameter
  * 
  * @param String
  *            ext
  */
 public static void deleteFile(String folder, String ext) {

  GenericExtFilter filter = new GenericExtFilter(ext);
  File dir = new File(folder);

  // list out all the file name with .txt extension
  String[] list = dir.list(filter);

  if (list.length == 0)
   return;

  File fileDelete;

  for (String file : list) {
   String temp = new StringBuffer(folder).append(File.separator)
     .append(file).toString();
   fileDelete = new File(temp);
   boolean isdeleted = fileDelete.delete();
  }
 }

 /**
  * lớp filter để để lọc các file có đuôi mở rộng là một parameter được
  * truyền vào trong constructor method
  */
 public static class GenericExtFilter implements FilenameFilter {

  private String ext;

  public GenericExtFilter(String ext) {
   this.ext = ext;
  }

  public boolean accept(File dir, String name) {
   return (name.endsWith(ext));
  }
 }

}



Thks & Rgds!!!

Không có nhận xét nào:

Đăng nhận xét