将一个目录及其子目录下的所有TXT类型的文本文档的内容合并到若干个新的文本文档中.当第一个新文本文档中的内容达到1M时,就把剩下的内容存储到第二个文本文档中,依次往下.这个程序我想了半天都写不出来,太笨了,请问大家应该怎么写?

解决方案 »

  1.   

    没有分不怕,怕的是用分来骗大家.
    请养成结贴的好习惯。这题的思路是:
    用File类的list()方法得到当前目前下的所以文件和目录,isDirectory()把其中的目录找出来,做递归调用。用list(FilenameFilter filter)得到那些.txt文件,对这些文件做读入和写出操作就可以了。写出时用一个计数器对写出的字符做统计(必要的话要分全角和半角),1M时换一个文件写。结果文件可以用文件名_数字。txt的格式来构造。
      

  2.   

    用read(byte[] b,
                    int off,
                    int len)
    off每次加100, len为100,b每次换个数组,用二维的也行!咋地都行
      

  3.   

    方法一:
    package zidom;import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;/**
     * 方法一是用传统IO包,但是速度没有使用NIO的速度快
     * 
     * @author zidom <br>
     *         电子邮件{@link [email protected]}
     * 
     */
    public class Main { /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
    long l = System.currentTimeMillis();
    File f = new File("C:/doc");
    readAndSplitFile(f);
    // 最后把不足1M的内容也保存
    saveByteArrayToFile(BUFFER);
    System.out.println(System.currentTimeMillis() - l);
    } /**
     * @throws FileNotFoundException
     * @throws IOException
     */
    private static void readAndSplitFile(File dir)
    throws FileNotFoundException, IOException {
    if (!dir.exists()) {
    throw new FileNotFoundException();
    } // 递归读取
    if (dir.isDirectory()) {
    File[] files = dir.listFiles();
    for (File file : files) {
    readAndSplitFile(file);
    }
    } else if (dir.getName().endsWith("txt")) {
    BufferedInputStream bos = new BufferedInputStream(
    new FileInputStream(dir));
    int size = 0; while (size != -1) {
    if (POS == SIZE) {
    saveByteArrayToFile(BUFFER);
    POS = 0;
    } else {
    if (size != -1) {// 解除一个小bug
    POS = POS + size;
    }
    }
    size = bos.read(BUFFER, POS, SIZE - POS);
    } bos.close();
    }
    } public static void p(Object o) {
    System.out.println(o);
    } /**
     * 保存1M的数据到一个文件中
     * 
     * @param buffer
     */
    static void saveByteArrayToFile(byte[] buffer) {
    File file = new File("C:/temp/" + fileNmae++ + ".txt"); try {
    if (!file.exists()) {
    file.createNewFile();
    }
    BufferedOutputStream bos = new BufferedOutputStream(
    new FileOutputStream(file));
    bos.write(buffer, 0, POS);
    bos.flush();
    bos.close();
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }
    } private static int fileNmae = 0;
    private final static int SIZE = 1024 * 1024;
    private static byte[] BUFFER = new byte[SIZE];
    private static int POS = 0;
    }方法二
    package zidom;import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.RandomAccessFile;
    import java.nio.ByteBuffer;
    import java.nio.channels.FileChannel;/**
     * 方法二是用NIO包,速度较普通IO包的速度快
     * 读取指定目录下的txt文件,
     * @author zidom <br>
     *         电子邮件{@link [email protected]}
     * 
     */
    public class MainNio {
    /**
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
    long l = System.currentTimeMillis();
    File f = new File("C:/doc");
    readAndSplitFile(f);
    // 最后把不足1M的内容也保存
    saveByteArrayToFile(BYTE_BUFFER);
    System.out.println(System.currentTimeMillis() - l);
    } /**
     * @throws FileNotFoundException
     * @throws IOException
     */
    private static void readAndSplitFile(File dir)
    throws FileNotFoundException, IOException {
    if (!dir.exists()) {
    throw new FileNotFoundException();
    } // 递归读取
    if (dir.isDirectory()) {
    File[] files = dir.listFiles();
    for (File file : files) {
    readAndSplitFile(file);
    }
    } else if (dir.getName().endsWith("txt")) {
    // 以只读方式创建一个随机访问 只读 (r)文件
    RandomAccessFile randomAccessFile = new RandomAccessFile(dir, "r");
    // 得到一个文件通道
    FileChannel fileChannel = randomAccessFile.getChannel();
    int size = 0;
    while (size != -1) {// 文件没有读到末尾
    if (BYTE_BUFFER.position() == BYTE_BUFFER.capacity()) {
    // 如果缓冲区中已经有1M的数据,则写入一个文件
    saveByteArrayToFile(BYTE_BUFFER);
    // 清除此缓冲区。将位置设置为 0,将限制设置为容量
    BYTE_BUFFER.clear();
    }
    // 将读取到文件中size个字节数到缓冲区
    size = fileChannel.read(BYTE_BUFFER);
    }
    }
    } /**
     * 保存1M的数据到一个文件中
     * 
     * @param buffer
     */
    static void saveByteArrayToFile(ByteBuffer buffer) {
    File file = new File("C:/temp/" + fileNmae++ + ".txt"); try {
    if (!file.exists()) {
    file.createNewFile();
    }
    // 以只读方式创建一个随机访问读写(w)文件
    RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
    // 得到一个文件通道
    FileChannel fileChannel = randomAccessFile.getChannel();
    // 反转此缓冲区。首先将限制设置为当前位置,然后将位置设置为 0。
    buffer.flip();
    // 将数据写入管道
    fileChannel.write(buffer);
    fileChannel.close();
    randomAccessFile.close();
    } catch (Exception e) {
    throw new RuntimeException(e);
    }
    } private static int fileNmae = 0;
    private final static int SIZE = 1024 * 1024;
    private static ByteBuffer BYTE_BUFFER = ByteBuffer.allocate(SIZE);
    }
      

  4.   

     下载分和论坛分是分开的。
    学习楼上的NIO说真的从1.4学习开始就没有用过,果然还是不行啊
      

  5.   

    额....LZ是要把下载下来的TXT电子书重新搞到一片文件里面方便读取吧.....
    哈哈...我当时特地自己做了一个....就是为了把一片电子书搞成另一片固定大小的电子书....
    效率不高.....没办法...咱水平有限package my.code;import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.FilenameFilter;
    import java.io.PrintWriter;/**
     * 
     * @author Kreo
     * 重新设定文件大小的程序,可以把原目录下所有指定扩展名的文件全部根据制定大小输出到指定文件夹,
     * 其中新的文件为 XXX0000.txt XXX0001.txt ......
     * 当然也可以设定后面数字的位数
     * 
     */
    public class ReSizeFileInDirectoryFile { private String dir = "E:/sec/book/trying/"; //原来的TXT的路径..下面所有TXT文件全部都会检测
    private String newDir = "E:/sec/book/finish/盘龙/"; //保存的目录..程序启动时会清空..所以.....
    private String fileNameStart = "盘龙"; // 新文件前缀
    private int newFileSize = 1024 * 128; //新文件的大小....
    private String extension = "txt"; //
    private int seq = -1; public ReSizeFileInDirectoryFile() {
    try {
    init();
    op();
    } catch (Exception e) {
    e.printStackTrace();
    }
    } /**
     * 
     * @param extension
     *            扩展名,将同时改变文件过滤及输入文件的扩展名条件
     */
    public ReSizeFileInDirectoryFile(String extension) {
    try {
    init();
    this.extension = extension;
    op();
    } catch (Exception e) {
    e.printStackTrace();
    }
    } /**
     * 工具初始化,把输出目录清空,如输出路径不存在,则执行输出目录的创建工作
     * 
     * @throws Exception
     */
    private void init() throws Exception {
    // Create newDir
    File newf = new File(newDir);
    // if exist ,then need clear
    if (newf.exists()) {
    delFiles(newf);
    newf.mkdirs();
    } else
    newf.mkdirs();
    } /**
     * 工具的具体操作方法,把文件按设定大小输出
     * 
     * @throws Exception
     */
    private void op() throws Exception {
    StringBuffer sb = new StringBuffer();
    for (File f : getFiles()) {
    sb.append(readFile(f));
    while (sb.length() > newFileSize) {
    writeFile(sb.substring(0, newFileSize));
    sb.delete(0, newFileSize);
    }
    }
    writeFile(sb.toString());
    } /**
     * 读取文件内容
     * 
     * @param f
     * @return
     * @throws Exception
     */
    private String readFile(File f) throws Exception {
    BufferedReader in = new BufferedReader(new FileReader(f));
    String tmp;
    StringBuffer sb = new StringBuffer();
    while ((tmp = in.readLine()) != null) {
    sb.append(tmp + "\r\n");
    }
    return sb.toString();
    } /**
     * 写入文件内容
     * 
     * @param s
     * @throws Exception
     */
    private void writeFile(String s) throws Exception {
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(getNextFile(4))));
    out.print(s);
    out.close();
    System.out.println("创建完成");
    } /**
     * 读取文件列表
     * 
     * @return
     */
    private File[] getFiles() {
    File f = new File(dir);
    if (f.exists()) {
    return f.listFiles(new FilenameFilter() {
    public boolean accept(File file, String s) {
    return s.matches(".*\\." + extension + "\\b");
    }
    });
    } else
    return new File[0];
    } /**
     * 得到下一个应该生成的File对象
     * 
     * @param digit
     *            表示生成文件名的长度,比如digit=4,则文件名依次为0000,0001,0002....如seq超出了设定位数,则不做改变
     * @return
     */
    private File getNextFile(int digit) {
    String fname = "";
    seq++;
    int n = 0;
    int m = seq;
    while (true) {
    m = m / 10;
    n++;
    if (m == 0)
    break;
    }
    if (digit > n) {
    for (int i = 0; i < digit - n; i++) {
    fname += "0";
    }
    }
    fname = newDir + fileNameStart + fname + seq + "." + extension;
    System.out.println("开始创建新文件:" + fname);
    return new File(fname);
    } /**
     * 删除一个目录树,包括目录本身
     * 
     * @param f
     * @throws Exception
     */
    private void delFiles(File f) throws Exception {
    if (f == null) {
    throw new NullPointerException("File is not initialization!");
    } else {
    File[] files = f.listFiles();
    if (files == null || files.length == 0) {
    f.delete();
    } else {
    for (File file : files) {
    if (file.isFile()) {
    file.delete();
    } else if (file.isDirectory()) {
    delFiles(file);
    file.delete();
    } else {
    try {
    file.delete();
    } catch (Exception e) {
    throw new NullPointerException("No such a file or directory!");
    }
    }
    }
    f.delete();
    }
    }
    } /**
     * @param args
     */
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    new ReSizeFileInDirectoryFile();
    }}
      

  6.   

    关键看文件是否是ACSII编码。如果是,那程序就会简化很多。
    如果不是,我写了一段代码,楼主可以参考一下。public class FileOutputStreamWrapper extends FileOutputStream {
    private long count = 0; public FileOutputStreamWrapper(String name) throws FileNotFoundException {
    super(name);
    } public void write(byte[] b, int off, int len) throws IOException {
    super.write(b, off, len);
    count+=len;
    } public void write(byte[] b) throws IOException {
    super.write(b);
    count+=b.length;
    } public void write(int b) throws IOException {
    super.write(b);
    count++;
    } public long getWrittenBytes(){
    return count;
    }

    public static void main(String[] args) throws Exception {
    String destFolder = "C:\\Megered";//楼主准备要合并文件的文件夹。
    String rescFolder = "C:\\TestFolder";//合并后放置的文件夹。
    String baseFileName = "meger_";//合并后的文件名称。
    final int MAX_SIZE = 1 << 20;// 文件的最大长度,1M字节。
    final String CHARSET_NAME = "GBK";//文件编码。
    Vector ins = new Vector();
    collectFiles(new File(rescFolder), ins);
    SequenceInputStream sis = new SequenceInputStream(ins.elements());
    String line = null;
    int count = 1;
    StringBuffer sb = new StringBuffer();
    sb.append(destFolder).append(File.separatorChar).append(baseFileName).append(count).append(".txt");
    FileOutputStreamWrapper fosw = new FileOutputStreamWrapper(sb.toString());
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fosw,CHARSET_NAME));
    BufferedReader br = new BufferedReader(new InputStreamReader(sis,CHARSET_NAME));
    while ((line = br.readLine()) != null) {
    bw.write(line);bw.flush();bw.newLine();
    if(fosw.getWrittenBytes()>=MAX_SIZE){
    bw.close();
    sb.delete(0, sb.length());
    sb.append(destFolder).append(File.separatorChar).append(baseFileName).append(count).append(".txt");
    fosw = new FileOutputStreamWrapper(sb.toString());
    bw = new BufferedWriter(new OutputStreamWriter(fosw,CHARSET_NAME));
    }

    }
    } public static void collectFiles(File folder, Vector ins)
    throws FileNotFoundException {
    File[] files = folder.listFiles();
    if (files == null || files.length <= 0)
    return;
    for (int i = files.length - 1; i >= 0; i--) {
    if (files[i].isFile() && files[i].getName().endsWith(".txt")) {
    ins.add(new FileInputStream(files[i]));
    } else if (files[i].isDirectory()) {
    collectFiles(files[i], ins);
    }
    }
    }
    }