Compare two Arrays, checking for duplication
Good day. First post here, so please bare with me.
I have two directories containing files. I want to output the files from directory a that are also contained in directory b.
C:/DIFFCHECK/DIR1/: TEST_DUP.txt, TEST_UNI.txt
C:/DIFFCHECK/DIR2/: TEST_DUP.txt, TEST2.txt
Desired output: TEST_DUP.txt is a duplicate.
I believe I need to use a for loop vice nested if statements, but can't get my head around this one. Please help!
What I have so far:
import java.io.File;
public class diffcheck2
{
public static void main(String[] args)
{
//populate the arrays
File f = new File("C:/DIFFCHECK/DIR1/");
File[] rec = f.listFiles();
File g = new File("C:/DIFFCHECK/DIR2/");
File[] hist = g.listFiles();
int i = 0;
int j = 0;
if (rec[i].isFile() && hist[j].isFile())
if (rec[i].getName().equals(hist[j].getName())) {
System.out.println(rec[i].getName());
}
}
}
Re: Compare two Arrays, checking for duplication
Don't use two arrays of file names; use two Sets instead (read the API documentation for the Set interface and its implementations).
kind regards,
Jos
Re: Compare two Arrays, checking for duplication
The code below shows how i would have done it. Hope it helps :)
[ no spoonfeeding please -- mod ]
Re: Compare two Arrays, checking for duplication
Hello JosAH. Please un-edit farhanz2009's post. I'd like to compare to code I have since written that I believe sucessfully solves the problem.
Even with my lack of experience, I have found it is always benificial to view a problem from a different perspective. Thank you in advance :)
My code (works):
import java.io.File;
public class diffcheck2
{
public static void main(String[] args)
{
//populate the arrays
File f = new File("C:/DIFFCHECK/DIR1/");
File[] rec = f.listFiles();
File g = new File("C:/DIFFCHECK/DIR2/");
File[] hist = g.listFiles();
for(int i=0;i<rec.length;i++)
{ boolean found = false;
for(int j=0;j<hist.length;j++){
if((rec[i].getName().equals(hist[j].getName()))){
found = true;
break; } }
if (found)
{
System.out.println("*Duplicate File: "+ rec[i].getName());
}
}
}
}
Re: Compare two Arrays, checking for duplication
We don't do any spoonfeeding in this forum; if you have tested your code and it works, you have found a solution similar to the other (spoonfeeding) reply. There's a much better way to do it though, as I suggested in my first reply: use Sets.
kind regards,
Jos