fsharpsquare fsharpsquare - 16 days ago 4
Java Question

while loop and printwriter only writes one line to file

I have made a code of which gets a bunch of data from different files in a folder, I have then made sure to only look for a certain kind of word in the files. Then I have made sure the code prints out the results in the console.

All the things I have done up till now works perfectly, but here comes the issue. I want the code to also print/write the information to a .txt file. This sort of works, but it only prints one of the many lines from the different files. I am completely sure that there are more that one as the console print shows at least 20 different lines containing the right word.
I am not completely sure where I have gone wrong, I have also tried to add the

.flush();
right before the
.close();
but it still wont work. I have also tried to add the
pToDocu.close();
underneath the
sc.close();
, but that doesn't work either, as that doesn't even write anything, that just creates a blank file.

So in short the code is supposed to write a bunch of lines, but it only writes one.

public static void lisFilesF(final File folderV) throws IOException {
PrintWriter pTD = new PrintWriter("eFile.txt");
for (final File fileEntry : folderV.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
System.out.println(fileEntry.getName());
try {
Scanner sc = new Scanner(fileEntry);
while (sc.hasNextLine()) {
String s = sc.nextLine();
if(s.contains("@"))
{
System.out.println(s);
pTD.println(s);
pTD.close();
}
}
sc.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}


UPDATE



I have changed the code to now have the
pTD.close();
outside of the while loop like seen below. Only issue is that the file which is created now is blank, it has no information inside it.

public static void lisFilesF(final File folderV) throws IOException {
PrintWriter pTD = new PrintWriter("eFile.txt");
for (final File fileEntry : folderV.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
System.out.println(fileEntry.getName());
try {
Scanner sc = new Scanner(fileEntry);
while (sc.hasNextLine()) {
String s = sc.nextLine();
if(s.contains("@"))
{
System.out.println(s);
pTD.println(s);
}
}
sc.close();
pTD.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

Answer

You are closing the file (pTD) after the first time you write to it. You should extract the close() call from the loop and move it after it:

Scanner sc = new Scanner(fileEntry);
while (sc.hasNextLine()) {
    String s = sc.nextLine();
    if(s.contains("@")) {
        System.out.println(s);
        pTD.println(s);
    }
}
sc.close();
pTD.close();