i want a code in java in order to compare contents of two files in java
how to compare contents of two files in java?
Collapse
X
-
Hi afroz!
We won't write that code for you, but we can help you write it yourself. But first of all, we need to know what the output should be. I can think of two possibilities:- The output is either "true" or "false", depending on if they are the same or not.
- The differences are listed, maybe with some detail. A bit like diff maybe.
Some general advice: We have an article on reading (and writing to) files here, you should read that.
Greetings,
Nepomuk -
Hi!
Although you're not the original poster, I'd be happy to explain. ^^
So, first of all, let's assume you have two files you want to compare like these ones:- file1.txt:Code:
This is my first file
- file2.txt:Code:
This is my second file
The second attempt would give you an output something likeWhich means "compared to the first file, the second file had the line 'my first' removed and had the line 'my second' inserted." This kind of comparison is much more complex, as if you were to change file2.txt toCode:< my first > my second
the output would be something likeCode:This is my second absolutely brilliant file
so it can even recognise that line 3 in file1.txt and line 4 in file2.txt are the same. Now to do something like that, you'll probably have to read in one of the files line by line, save them to some kind of container and then read the other file line by line and check, if the line you just read was already in the first file. So, much more complicated.Code:< my first > my second > absolutely brilliant
Greetings,
NepomukComment
- file1.txt:
Comment