复制和合并两个文件

时间:2014-02-15 10:03:41

标签: java file

我正在使用java文件流。我有两个文件。第一个文件可能是空的也可能不是。第二个文件包含字符串和浮点数。如果第一个文件为空,那么我想复制其中的第二个文件。否则我想合并文件。

尝试了RandomAccessFile,但它无效。

3 个答案:

答案 0 :(得分:0)

如果要复制文件,请使用

public static Path copy(Path source,
        Path target,
        CopyOption... options)
                 throws IOException

File.copy()

如果要合并它们,请在写入模式下打开文件,在该模式下要附加附加模式的数据。

BufferedWriter bw = new BufferedWritr(new FileWriter("file.txr",true));

然后在bw中写入您从源文件中读取的数据。

答案 1 :(得分:0)

我的解决方案如下:

public void CopyFile(File one, File two) throws IOException {

    // Declare the reader and the writer        
    BufferedReader in = new BufferedReader(new FileReader(one));
    BufferedWriter out;

    String contentOfFileOne = "";

    // Read the content of the first file
    while(in.ready()){
        contentOfFileOne += in.readLine();
    }

    // Trim all whitespaces
    contentOfFileOne.trim();

    // If the first file is empty
    if(contentOfFileOne.isEmpty()){

        // Create a new Writer to the first file and a reader
        // from the second file
        in.close();
        out = new BufferedWriter(new FileWriter(one));
        in = new BufferedReader(new FileReader(two));

        while(in.ready()){
            String currentLine = in.readLine();
            out.write(currentLine);
        }

        // Close them accordingly
        in.close();
        out.close();

    } else {

        // If the first file contains something

        in.close();
        out = new BufferedWriter(new FileWriter(one,true));
        in = new BufferedReader(new FileReader(two));


        // Copy the content of file two at the end of file one
        while(in.ready()){
            String currentLine = in.readLine();
            out.write(currentLine);
        }

        in.close();
        out.close();

    }
}

评论应解释功能。

答案 2 :(得分:0)

我认为这应该是最有效的选择

    FileChannel f1  = FileChannel.open(Paths.get("1"), StandardOpenOption.APPEND);
    FileChannel f2  = FileChannel.open(Paths.get("2"));
    f1.transferFrom(f2, f1.size(), Long.MAX_VALUE);