Good evening,
I am entirely new to asking questions here, so sorry if I did this wrong. I am trying to append one whole .txt file to end of another one, on a new line, without rewriting the contents.
For example, I have this in one.txt
TEST 1 00001 BCOM
and I have this in two.txt,
TEST 2 00001 BCOM
This is the only working code I found that would copy/overwrite to another file, All others I've copied, reworked with file paths and names and tried and it doesn't work for me. I am still a beginner in Java.
import java.io.*;
class CompileData {
public static void main(String args[]) {
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader("one.txt");
fw = new FileWriter("two.txt");
int c = fr.read();
while(c!=-1) {
fw.write(c);
c = fr.read();
}
} catch(IOException e) {
e.printStackTrace();
} finally {
close(fr);
close(fw);
}
}
public static void close(Closeable stream) {
try {
if (stream != null) {
stream.close();
}
} catch(IOException e) {
}
}
}
With this code, instead of getting this for two.txt
TEST 1 00001 BCOM
TEST 2 00002 BCOM
I only get for two.txt
TEST 1 00001 BCOM
Any help, tips, pointers and answers will be gladly appreciated!
For this, you can use append feature of FileWriter - by calling the parameterized constructor which accept the boolean whether to append or not.
Check here File Writer - append
Output
TEST 2 00002 BCOM
TEST 1 00001 BCOM
If you would like to append in start of file, you can use RandomAccessFile to append in desired location. More details here - RandomAccessFile API