我想读取一个文件,并根据某些条件将一些文本附加到同一个文件中。这是我的代码。
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();
}
}
}
此代码工作正常。问题是,输出与输入文件不完全相同。输入文件中我追加一些内容的多行被写入输出文件中的同一行。
例如,我为这些元素添加了一个id属性,它被添加但输出被写为一行。
<input type="submit" <%=WebConstants.HTML_BTN_SUBMIT%> value="Submit" />
<input type="hidden" name="Page" value="<%=sAction%>" />
<input type="hidden" name="FileId" value="" />
我的问题是,我做错了什么,以致格式化搞砸了?
如果是这样,是否可以完全按输入文件进行打印?
非常感谢帮助。在此先感谢:)
答案 0 :(得分:1)
要解决您的问题,只需在您要写入的每一行添加一个额外的行分隔符(\n
)。
所以:writeToFile.add(readLine);
变为:writeToFile.add(readLine+"\n");