I'm wondering if the way I'm reading file1 and adding it to the buffer is incorrect?
My idea is to add the contents of file 1 to a buffer.
Read and write the content of file2 to file1
Write the buffer which contains the content of file1 back to file 1. Use append = true so the content will be added to the end (so after the content of file2)
Where do I go wrong?
package com.codegym.task.task18.task1819;
/*
Combining files
TODO: Write the contents of the second file to the beginning of the first file
so that the files are combined.
*/
import java.io.*;
public class Solution {
public static void main(String[] args) throws IOException {
//TODO: read 2 files from the console
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String file1 = reader.readLine();
String file2 = reader.readLine();
reader.close();
byte[] buffer = new byte[file1.length() + file2.length()];
//TODO: Create an input stream for the first file and read its contents.
FileInputStream inputStreamFile1 = new FileInputStream(file1);
//read a bytes from file1 and putting them in a buffer
while( inputStreamFile1.available() > 0) {
int i = 0;
buffer[i++] = (byte) inputStreamFile1.read();
}
inputStreamFile1.close();
//TODO: Then create an output stream for the first file.
// And an input stream for the second file.
FileOutputStream outputStreamFile1 = new FileOutputStream(file1, true);
FileInputStream inputStreamFile2 = new FileInputStream(file2);
//TODO: The contents of the first and second files must be combined in the first file.
//read the contents of file2 and write the contents to file1
while (inputStreamFile2.available() > 0) {
outputStreamFile1.write(inputStreamFile2.read());
}
//write all the bytes that are added to the buffer from file 1 back to the file1
outputStreamFile1.write(buffer);
outputStreamFile1.close();
inputStreamFile2.close();
}
}