Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

java - how can i Merge files

How can i wright in the beggining of the first file infomation which contains in second file, so that they merge each other?? please help, thanks.

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();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This can be done in pure Java... It reads the second file and appends to the first file.
Keep in mind, that this will not work for large files, since it saves all of fileA content into memory.

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("
");
    }
    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("
");
    }
    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();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...