Reputation: 1443
I want to read a file and append some text to the same file based on some criteria. This is my code.
public static void writeOutputToFile(ArrayList<String> matchingCriteria) {
//Provide the folder which contains the files
final File folder = new File("folder_location");
ArrayList<String> writeToFile = new ArrayList<String>();
//For each file in the folder
for (final File fileEntry : folder.listFiles()) {
try (BufferedReader br = new BufferedReader(new FileReader(fileEntry))) {
String readLine = "";
while ((readLine = br.readLine()) != null) {
writeToFile.add(readLine);
}
try (FileWriter fw = new FileWriter(fileEntry); BufferedWriter bw = new BufferedWriter(fw)) {
for (String s : writeToFile) {
boolean prefixValidation = false;
//Check whether each line contains one of the matching criterias. If so, set the condition to true
for (String y : matchingCriteria) {
if (matchingCriteria.contains(y)) {
prefixValidation = true;
break;
}
}
//Check if the prefixes available in the string
if (prefixValidation) {
if (s.contains("name=\"") && !(s.contains("id=\""))) {
//Split the filtered string by ' name=" '
String s1[] = s.split("name=\"");
/*Some Code*/
//Set the final output string to be written to the file
String output = "Output_By_Some_Code";
//Write the output to the file.
fw.write(output);
//If this action has been performed, avoid duplicate entries to the file by continuing the for loop instead of going through to the final steps
continue;
}
}
fw.write(s);
bw.newLine();
}
fw.flush();
bw.flush();
//Clear the arraylist which contains the current file data to store new file data.
writeToFile.clear();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
This code works fine. The problem is, the output is not exactly as the input file.The multiple lines in the input file which I append some content is written to the same line in the output file.
For example,I add an id attribute for these elements and it gets added but the output is written as a single line.
<input type="submit" <%=WebConstants.HTML_BTN_SUBMIT%> value="Submit" />
<input type="hidden" name="Page" value="<%=sAction%>" />
<input type="hidden" name="FileId" value="" />
My question is, am I doing something wrong so that formatting is getting messed up?
If so, is there something to do to print exactly as the input file?
A help is much appreciated. Thanks in advance :)
Upvotes: 2
Views: 714
Reputation: 19910
To solve your problem, just add an additional Line-Separator (\n
) to every line you want to write.
So this: writeToFile.add(readLine);
becomes this: writeToFile.add(readLine+"\n");
Upvotes: 1