File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes I/O and Streams and the fly likes compare two text files Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "compare two text files" Watch "compare two text files" New topic

compare two text files

cool dude

Joined: Jun 19, 2007
Posts: 1
i am comparing two text file by checking occurance of a line in file 1 by comparing it with each line in file 2(not line by line)
i have to print in 3rd text file as difference
please see my progrm and tell me modification required

package comp.vnet.comparator;

import comp.vnet.comparator.NewFile;

class FileComparator {
public static void main(String[] args) throws IOException{

String file1,file2,String1,String2;
BufferedReader br1,br2;
int fileCount1=0;
int fileCount2=0;
br1= new BufferedReader(new InputStreamReader (;

// File file = new File ("output.txt");
FileWriter fstream = new FileWriter("out.txt");

// FileOutputStream fo = new FileOutputStream("E:/Filecomparator/FileComparator/output.txt");
System.out.println("Enter First file name");
System.out.println("Enter Second file name");
NewFile nf= new NewFile();

while ((String1= br1.readLine()) != null) {
while ((String2= br2.readLine()) != null) {
System.out.println("fileCount1+ : " + fileCount1);
System.out.println("fileCount2+ : " + fileCount1);

BufferedWriter out = new BufferedWriter(fstream);

for(int i=0;i<=fileCount1;i++)
for(int j=0;j<fileCount2;j++)
if ( String1.equals (String2) ) {
System.out.println("the line is equal");





Joe Ess

Joined: Oct 29, 2001
Posts: 9190

Welcome to the JavaRanch, Cool Dude.
First, you must have missed our naming policy on the way in. To keep things friendly around here we ask that people use their real name, that is, a first and last name, seperated by a space and not obviously fake. You can change your displayed name here. Thanks for your prompt attention.
Second, we get a lot of people coming here with schoolwork so we ask that you Do Your Own Homework. Have a look at our FAQ: How To Ask Questions On JavaRanch and feel free to come back with any specific questions you have.

[How To Ask Questions On JavaRanch]
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
You can probably Google on "text diff java" and find a lot of tips on algorithms. There are some serious "computer science" solutions that are so compact I have no idea what they do, and some that make more sense. Let us know what you find!

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
I agree. Here's the link:
subject: compare two text files
It's not a secret anymore!