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();
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();
I would try debugging the code line by line and check what is exactly being written to the second, third etc. file (maybe the file writing is OK, but empty strings are being written?).
Also check:
Debugging Java code line by line
Java read in single file and write out multiple files
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.