我想读取文件,并根据某些条件将一些文本附加到同一文件中。这是我的代码。
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="" />
我的问题是,我做错什么了吗,以致格式混乱了?
如果是这样,是否需要做一些与输入文件完全相同的打印?
非常感谢您的帮助。提前致谢 :)
要解决您的问题,只需在\n
要编写的每一行中添加一个额外的行分隔符()。
所以这个:writeToFile.add(readLine);
变成这个:writeToFile.add(readLine+"\n");
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句