日期:2014-05-20 浏览次数:20762 次
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.List; public class Test1 { static File file = new File("D:\\11"); static List<File> lists = new ArrayList<File>();// 存储所有.txt文件的绝对路径 /** * 将所有文件合并到同一个文件当中 * * @throws Exception */ public static void uniteFile() throws Exception { File newFile = new File("D:\\11\\final.txt"); FileReader fr; FileWriter fw = new FileWriter(newFile, true); ; BufferedReader bufr = null; BufferedWriter bufw = new BufferedWriter(fw); for (File file : lists) { fr = new FileReader(file); bufr = new BufferedReader(fr); String len = bufr.readLine(); while (null != len) { bufw.write(len); bufw.flush(); len = bufr.readLine(); } } bufw.close(); bufr.close(); } /** * 将文件按照1KB分割 * * @param f * @throws Exception */ public static void divideFile() throws Exception { FileInputStream fis = new FileInputStream("D:\\11\\final.txt"); FileOutputStream fos = null; byte[] b = new byte[1024]; for (int i = 1;; i++) { if (fis.read(b) == -1) { break; } int length = fis.read(b); File smallfile = new File("D:\\11\\22\\33\\" + i + ".txt"); fos = new FileOutputStream(smallfile); fos.write(b); System.out.println("写入文件" + i + "成功!"); } fos.close(); fis.close(); } public static void seekTxt(File f) { File[] files = f.listFiles(); for (File file : files) { if (file.isDirectory()) { seekTxt(file); } else { if (file.getName().split("\\.")[1].equals("txt")) { lists.add(file); } } } } public static void main(String[] args) throws Exception { seekTxt(file); uniteFile(); divideFile(); } }