hi,
here is how i would do:
i propose you to read the lines of the first file to a Vector (or thelike) first.
then read all the lines of the second file and compare if the vector already contains this line. if not: add it, if yes: drop it.
after that, you have a vector which contains unique lines of text and all you have to do is to write them back to another file.
i have my good day so i added some code :-) , this should work.
- the exception handling is not very apropriate: just one big tray/catch clause is bad style.....
- consider doing it static
- if you got huge files (some megs), then you get a very big vector.......this could slow donw the thing. perhaps ArrayList could help you there, it is faster (not synchronized)....
hope that helps and hope i did not confuse you :-)
dont go any further if you want to do it yourself ......................
<pre>
import java.io.*;
import java.util.*;
public class Demo {
/**
*
*/
static public void main(String[] args) {
Demo d = new Demo();
File f1 = new File("e:\\a.txt");
File f2 = new File("e:\\b.txt");
File f3 = new File("e:\\c.txt");
d.mergeFiles(f1, f2, f3);
}
public void mergeFiles(File f1, File f2, File destFile) {
try {
Vector temp = new Vector();
BufferedReader br;
String line;
// read the first file
br = new BufferedReader(new FileReader(f1));
line = br.readLine();
// read all lines of first file to a temporary vector
while (line != null) {
// add it to the vector
temp.add(line);
// read next line
line = br.readLine();
}//end while
// no we read the second file
br = new BufferedReader(new FileReader(f2));
line = br.readLine();
// read all lines of first file to a temporary vector
while (line != null) {
// is this line contained in the first file ?
if (!temp.contains(line)) {
// no, it isnt. lets add it to the vector
temp.add(line);
} else {
// just for demo.....this is a duplicate line
// do nothing
}
// read next line
line = br.readLine();
}//end while
// cleanup
br.close();
// at this point, the vector should contain unique lines. lets write it back to a file
PrintWriter pw = new PrintWriter(new FileWriter(destFile)

;
Enumeration en = temp.elements();
String outLine;
// enumerate through vector. (you could also use the indexes in a for loop...)
while (en.hasMoreElements()) {
// get nect element in vector
outLine = (String) en.nextElement();
// write the line
pw.println(outLine);
}
// dont forget to close writer
pw.close();
} catch(Exception e) {
System.out.println("Exception occured: "+e);
e.printStackTrace();
}
}
}
</pre>
karl