gpt4 book ai didi

java - 读取和写入同一文件 - 输出格式更改

转载 作者:行者123 更新时间:2023-11-30 10:23:33 25 4
gpt4 key购买 nike

我想读取一个文件并根据某些条件将一些文本附加到同一个文件中。这是我的代码。

 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");

关于java - 读取和写入同一文件 - 输出格式更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46952494/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com