[英]Read and Write to same file - Output format changes
我想读取一个文件并根据某些条件将一些文本附加到同一个文件中。 这是我的代码。
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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.