首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

把一个文件夹上文件分别归类

2012-09-27 
把一个文件夹下文件分别归类实用场景: 例如在一个文件目录下面文件很多,现在要把这么多的文件分别移动(剪

把一个文件夹下文件分别归类
实用场景: 例如在一个文件目录下面文件很多,现在要把这么多的文件分别移动(剪切)到各自的小目录下面,可以定制每个文件目录下存放的文件数量。

代码如下:

package com.test.file;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;/** * divide a heap of files into specified category *  * @author qgao */public class FileUtils {  public FileUtils() {  }  /**   * classify a heap of files ,store them in some folders each folder have the   * same number of files   *    * @param pathname   * @throws IOException   */  public void classifyFile(String pathname, int num, String prefix)      throws IOException {    if (num <= 0)      return;    File dir = new File(pathname);    File[] files = dir.listFiles();    int count = 0;    int folder = 0;    File tmpFolder = null;    for (int i = 0; i < files.length; i++) {      if (files[i].isFile()) {        if (count % num == 0) {          File temp =              new File(pathname + File.separator + prefix                  + String.valueOf(folder++));          temp.mkdir();          tmpFolder = temp;        }        this.cutFile(files[i], tmpFolder);        count++;      }    }  }  public void classifyFile(String pathname, String prefix) throws IOException {    this.classifyFile(pathname, 10, prefix);  }  public void classifyFile(String pathname) throws IOException {    this.classifyFile(pathname, 10, "");  }  /**   * cut a file from one folder to anther foler   *    * @param file the source file   * @param temp the target folder   * @throws IOException   */  public void cutFile(File file, File folderPath) throws IOException {    File srcFile = file;    if (srcFile.isFile()) {      File desFile =          new File(folderPath.getAbsolutePath() + File.separator              + srcFile.getName());      FileInputStream input = new FileInputStream(srcFile);      FileOutputStream output = new FileOutputStream(desFile);      try {        byte[] buffer = new byte[4096];        int n = 0;        while (-1 != (n = input.read(buffer))) {          System.out.println(n);          output.write(buffer, 0, n);        }      } finally {        try {          if (input != null) {            input.close();          }          if (output != null) {            output.close();          }        } catch (IOException e) {          e.printStackTrace();        }      }      srcFile.delete();    } else      return;  }}

热点排行