从多个文件中获取数据并移动到一个文件

时间:2014-11-09 07:59:25

标签: java file-io

我的一些代码采用名为wonder1.txt的文件,并将该文件中的日期写入另一个文件。假设我有更多文件,例如wonder2.txtwonder3.txtwonder4.txt。如何在同一个文件中编写其余部分。

import java.io.*;
import java.util.*;
import java.lang.*;

public class alice {

  public static void main(String[] args) throws FileNotFoundException, IOException {
    String fileName = ("/Users/DAndre/Desktop/Alice/wonder1.txt");
    BufferedReader br = new BufferedReader(new FileReader(fileName));
    try {
        StringBuilder stringBuilder = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            stringBuilder.append(line);
            stringBuilder.append("\n");
            line = br.readLine();
        }


        /**
         * Pass original file content as string to another method which
         * creates new file with same content.
         */
        newFile(stringBuilder.toString());
    } finally {
        br.close();
    }


  }

  public static void newFile(String fileContent) {
    try {
        String newFileLocation = "/Users/DAndre/Desktop/Alice/new1.txt";
        PrintWriter writer = new PrintWriter(newFileLocation);
        writer.write(fileContent);//Writes original file content into new file
        writer.close();
        System.out.println("File Created");
    } catch (Exception e) {
        e.printStackTrace();
    }
  }
}

1 个答案:

答案 0 :(得分:2)

如果你有文件列表,那么你可以逐个循环它们。您当前的代码在循环内移动。 更简单的方法是将所有文件放在一个文件夹中并从中读取。

这样的事情:

File folder = new File("/Users/DAndre/Desktop/Alice");

    for (final File fileEntry : folder.listFiles()) {
        String fileName = fileEntry.getAbsolutePath();
        BufferedReader br = new BufferedReader(new FileReader(fileName));
        try {
            StringBuilder stringBuilder = new StringBuilder();
            String line = br.readLine();

            while (line != null) {
                stringBuilder.append(line);
                stringBuilder.append("\n");
                line = br.readLine();
            }


            /**
             * Pass original file content as string to another method which
             * creates new file with same content.
             */
            newFile(stringBuilder.toString());
        } finally {
            br.close();
        }
    }