Search code examples
javano-duplicates

Java reading and writing to same file


I'm using the following code to search specific files in my computer and write the absolute path in a text file. My problem is that every time I run this code it add duplicate lines into text file, i want to add only those lines(file path) which are not written in the text file at that time (no duplicates).. Thank you

public static void walkin(File dir) {
    String pattern = ".mp4";
    try {

        PrintWriter out = new PrintWriter(new BufferedWriter(
                new FileWriter("D:\\nawaaaaaa.txt", true)));
        File listFile[] = dir.listFiles();
        if (listFile != null) {
            for (int i = 0; i < listFile.length; i++) {
                if (listFile[i].isDirectory()) {
                    walkin(listFile[i]);
                } else if (listFile[i].getName().endsWith(pattern)
                        && listFile[i].isFile()) {
                    System.out.println(listFile[i].getPath());
                    out.write(listFile[i].toString());
                    out.write("\r\n");
                    // out.close();
                } else {
                    walkin(listFile[i]);
                }
            }
        }
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}


Solution

  • Your code works for me, no idea what is the problem on your side, how you are calling it; but you can optimize your code a bit, something as follows (just very quick code, code be made nicer, but to give you an idea):

    public class SomeTest {
    
        private static HashSet<String> filez = new  HashSet<String> (); 
    
        public static void walkin(File dir, PrintWriter out) {
            String pattern = ".mp4";
            File listFile[] = dir.listFiles();
            if (listFile != null) {
                for (int i = 0; i < listFile.length; i++) {
                    if (listFile[i].getName().endsWith(pattern) && listFile[i].isFile()) {
                        //System.out.println(listFile[i].getPath());
                        if (filez.add(listFile[i].getPath())) {
                            out.write(listFile[i].toString());
                            out.write("\r\n");
                        }
                    } else {
                        walkin(listFile[i], out);
                    }
                }
            }
        }
    
        public static void main(String[] args) {
            try {
                File dir = new File("C:\\mydir");
                PrintWriter out = new PrintWriter(new BufferedWriter(
                        new FileWriter("D:\\nawaaaaaa.txt", true)));
                walkin(dir, out);
                out.close();
            } catch (IOException e) {
               //
            }
        }
    }
    

    You can use the filez hashset to print stuff, or write your file at the end of the parsing process as well.. your choice.