-2

Hey so I'm currently having an issue with this code: [There is more code to this but this is the block that I need help with]

    File fe = new File("C:\\Users\\" + System.getProperty("user.name") + "\\desktop" + "\\SearchResults.txt");
    String customLoca = "C:\\Users\\" + System.getProperty("user.name") + "\\desktop";



    File dir = new File(customLoca);
    for (File f : dir.listFiles()){
        if (f.getName().contains(".jar"))
        if (f.getName().endsWith(".jar"))
            try{

                FileWriter fw = new FileWriter(fe);
                fw.write("[!]Found: " + f.getName() + "[!]");
                fw.write("\r\n");
                fw.write("[!]Found: " + f.getName() + "[!]");
                fw.close();

            }catch(Exception ex){
    }

}
}

}

I want it to print all the results however it only prints 1.

https://gyazo.com/406ab3039f3efa8f72d3dfff5732c088

Do you know a way I can make it so it prints all the results? Thanks.

harry
  • 7
  • 1

1 Answers1

0

The problem is that you are creating the file writer object inside loop. so it will replace the previous result hence only the last result will be present in the searchResults.txt.

To fix this problem move FileWriter fw = new FileWriter(fe); outside the for loop

Also note that you dont need both the 2 if conditions.

if if (f.getName().contains(".jar")) is true then if (f.getName().endsWith(".jar")) also returns true, also you are missing the braces after the if statement.

File dir = new File(customLoca);
  for (File f : dir.listFiles()){
    if (f.getName().endsWith(".jar")) {
        try{

            FileWriter fw = new FileWriter(fe);
            fw.write("[!]Found: " + f.getName() + "[!]");
            fw.write("\r\n");
            fw.write("[!]Found: " + f.getName() + "[!]");
            fw.close();

        }catch(Exception ex){
}
}
}
Jobin
  • 5,610
  • 5
  • 38
  • 53