Search code examples
javafilefilereaderfileinputstreamfilewriter

How to copy content of a file to another file but at the top of the file in Java


I would liked to copy the content of file "Convert.sql" to file "Entity.sql" without overriding the "Entity.sql" file. This part i've been able to do it but in addition to that, i would liked the content of the file "Convert.sql" to be copied at the top of "Entity.sql" file and also not on the same line.

Ex: Convert.sql

Student

Employee

Ex: Entity.sql

Name

Address

Ex:Result

Student

Employee

Name

Address

Here is my code to copy content of a file to another file without overriding the file but it is being copied it on the same line which i don't want to.

package Final;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

public class Mainy {
    public static void main(String[] args) throws IOException {
        File dir = new File(".");

        String source = dir.getCanonicalPath() + File.separator + "Convert.sql";
        String dest = dir.getCanonicalPath() + File.separator + "Entity.sql";

        File fin = new File(source);
        FileInputStream fis = new FileInputStream(fin);
        BufferedReader in = new BufferedReader(new InputStreamReader(fis));

        FileWriter fstream = new FileWriter(dest, true);
        BufferedWriter out = new BufferedWriter(fstream);

        String aLine = null;
        while ((aLine = in.readLine()) != null) {
            //Process each line and add output to Dest.txt file
            out.write(aLine);
            out.newLine();
        }

        // do not forget to close the buffer reader
        in.close();

        // close buffer writer
        out.close();
    }
}

Can someone please help me out to do this?


Solution

  • Here a snippet which will do the job as you described

    Charset usedCharset = Charset.defaultCharset();
    
    // read all lines from Convert.sql into a list
    List<String> allLines = Files.readAllLines(Paths.get("Convert.sql"), usedCharset);
    
    // append all lines from Entity.sql to the list
    allLines.addAll(Files.readAllLines(Paths.get("Entity.sql"), usedCharset));
    
    // write all lines from the list to file Entity.sql
    Files.write(Paths.get("Entity.sql"), allLines, usedCharset);