我怎样才能合并文件

时间:2014-04-19 20:02:48

标签: java fileinputstream fileoutputstream

如何在第二个文件中包含的第一个文件信息的开头编写,以便它们相互合并?请帮助,谢谢。

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        FileInputStream fileReader = new FileInputStream(reader.readLine());
        FileOutputStream fileWriter = new FileOutputStream(reader.readLine(), true);
        while (fileReader.available() > 0) {
            int data = fileReader.read();
            fileWriter.write(data);
        }
        fileReader.close();
        fileWriter.close();
        reader.close();

2 个答案:

答案 0 :(得分:1)

只需使用

org.apache.commons.io.FileUtils.copyFile(srcFile, destFile);
//rename the file names if needed

或者您可以使用SequenceInputStream创建多个输入流的序列。

示例代码:

    File srcFile = new File("resources/abc.txt");
    File destFile = new File("resources/xyz.txt");

    File temp = new File("resources/temp.txt");

    try {
        FileInputStream fileInputStream1 = new FileInputStream(srcFile);
        FileInputStream fileInputStream2 = new FileInputStream(destFile);

        SequenceInputStream inputStream = new SequenceInputStream(fileInputStream1,
                fileInputStream2);
        FileOutputStream outputStream = new FileOutputStream(temp);
        byte[] buffer = new byte[1024];
        int read = -1;
        while ((read = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, read);
        }

        inputStream.close();
        outputStream.close();

        fileInputStream1.close();
        fileInputStream2.close();

        // here you can rename the temp file or delete a source file if needed
    } catch (IOException e) {
        e.printStackTrace();
    }

答案 1 :(得分:1)

这可以在纯Java中完成...... 它读取第二个文件并附加到第一个文件 请记住,这不适用于大型文件,因为它会将所有fileA内容保存到内存中。

Scanner reader = new Scanner(System.in);
System.out.println("Enter the first file path");
String fileA = reader.next();
System.out.println("Enter the second file path");
String fileB = reader.next();

try {

    // Read from and cache fileA
    StringBuilder cache = new StringBuilder();
    BufferedReader readerA = new BufferedReader(new FileReader(new File(fileA)));
    String line = null;
    while((line = readerA.readLine()) != null) {
        cache.append(line);cache.append("\n");
    }
    readerA.close();

    // Read from fileB and overwrite to fileA
    FileWriter writerB = new FileWriter(new File(fileA));
    BufferedReader readerB = new BufferedReader(new FileReader(new File(fileB)));
    line = null;
    while((line = readerB.readLine()) != null) {
        writerB.write(line);writerB.write("\n");
    }
    writerB.close();
    readerB.close();

    // Append original fileA content back into fileA
    FileWriter writerA = new FileWriter(new File(fileA), true);
    writerA.write(cache.toString());
    writerA.close();

} catch (Exception e) {
    e.printStackTrace();
}