【发布时间】:2018-04-07 17:28:47
【问题描述】:
我想读取一个文件并根据某些条件将一些文本附加到同一个文件中。这是我的代码。
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="" />
我的问题是,我是不是做错了什么导致格式混乱?
如果是这样,有什么办法可以完全按照输入文件打印吗?
非常感谢您的帮助。在此先感谢:)
【问题讨论】:
-
不是修复,但您不需要关闭您的读者/作者,因为您使用的是
try-with-resources-Statements -
谢谢。习惯的力量:)
-
所有内容都写在一行上吗?还是只有几行?
-
一些行。几乎总是我在附加一些内容的行。
-
将
writeToFile.add(readLine);替换为以下行时是否得到预期输出:writeToFile.add(readLine+"\n");
标签: java file-io bufferedreader