I am trying to make a Java application that will take in a bulk file with multiple messages, and then split them up and write each message to its own file. The issue that I am having is that its only creating a file with the last message inside, so I think it is overwriting for each iteration of the while loop. My code is below:
public void writeFile(StringBuilder contents, String outputFilePath) throws IOException {
String messages = contents.toString();
StringTokenizer st = new StringTokenizer(messages, "$");
FileWriter fileWriter = null;
BufferedWriter bufferedFileWriter = null;
while (st.hasMoreTokens()) {
int i = 0;
i++;
File output = new File(outputFilePath + "_" + i + ".txt");
try {
fileWriter = new FileWriter(output);
bufferedFileWriter = new BufferedWriter(fileWriter);
bufferedFileWriter.append(st.nextToken());
}
finally {
if (bufferedFileWriter != null) {
bufferedFileWriter.close();
}
if (fileWriter != null) {
fileWriter.close();
}
}
}
}
move the declaration of i
:
int i = 0;
outside the while
loop:
int i = 0;
while(st.hasMoreTokens(){
...
}
That way you're not overwriting it for every iteration. Leaving it always with the value of 1
.
An even better approach would be to use a for
:
for(int i = 1; st.hasMoreTokens(); i++){
...
}
Which leaves you with a nicely scoped variable i
only accessible inside the loop