W.Cointreau W.Cointreau - 3 months ago 17
Java Question

files are empty when writing multiple files

I'm trying to read one file and write several files after modifying a small point.

My code works while writing the first file, but the other files are empty files. :(

I think there is a problem when I use

bufferedwriter
and
filewriter
, but can't find what the problem is though I followed an advice to use
flush
from stackoverflow.

What is the problem in my code?

FileReader fr = new FileReader(FileDir);
BufferedReader br = new BufferedReader(fr);
for (String mc: matchedContents){
FileWriter fw = new FileWriter(saveFileDir+String.valueOf(matchedContents.indexOf(mc)+1)+".xml", false);
BufferedWriter bw = new BufferedWriter(fw);
while ((s = br.readLine())!=null){
// check if s has matched contents
if (s.contains(mc)){
String replacedString="";
if (mc.contains("NV"))
replacedString = s.replace(mc, "NV("+anyItem(edgeNames)+")");
else if (mc.contains("AW"))
replacedString = s.replace(mc, "AW("+anyItem(edgeNames)+")");
bw.write(replacedString);
bw.newLine();
}
else {
bw.write(s);
bw.newLine();
}
}
System.out.println(mc+" end");
bw.flush();
bw.close();
fw.close();
}
br.close();
fr.close();

Answer

Its because after the first file your bufferedReader comes to the end. To write again you need to reload the file to bufferedReader. So what you need to do is make the bufferedReader and the FileReader inside the for loop

    for (String mc: matchedContents){
        FileReader fr = new FileReader(FileDir);
        BufferedReader br = new BufferedReader(fr);
        FileWriter fw = new FileWriter(saveFileDir+String.valueOf(matchedContents.indexOf(mc)+1)+".xml", false);
        BufferedWriter bw = new BufferedWriter(fw);
        while ((s = br.readLine())!=null){
            // check if s has matched contents
            if (s.contains(mc)){
                String replacedString="";
                if (mc.contains("NV"))
                    replacedString = s.replace(mc, "NV("+anyItem(edgeNames)+")");
                else if (mc.contains("AW"))
                    replacedString = s.replace(mc, "AW("+anyItem(edgeNames)+")");
                bw.write(replacedString);
                bw.newLine();
            }
            else {
                bw.write(s);
                bw.newLine();
            }
        }
        System.out.println(mc+" end");
        bw.flush();
        bw.close();
        fw.close();
        br.close();
    }

    fr.close();