我需要读取一个文件并写入一个单独的文件。我还必须能够读取两个文件并将它们写入一个文件中。
File 1(To be read)
Header
text
text
Footer
File 2(To be read)
Header
Text12
Text12
Footer
Output file
Header
text
text
Text12
Text12
Footer
第一行和最后一行保持相同但仅附加中间行。 根据我的代码。页眉和页脚会附加两次。
My output :
Header
text
text
Footer
Header
Text12
Text12
Footer
My Code :
for (int i = 0; i < template.length; i++) {
String endTime = findEndTime(startTime, duration);
File file = new File(foldername);
file.createNewFile();
BufferedWriter bw = new BufferedWriter(new FileWriter(
foldername + "/" + solfilename, true));
BufferedWriter bsftp = new BufferedWriter(new FileWriter(
"c:/ToolSOlFile/" + solfilename, true));
try {
String verify, putData = null,header=null,footer=null;
FileReader fr = new FileReader("C:/ToolSOlFile/Templates/"+ template[i]);
BufferedReader br = new BufferedReader(fr);
while ((verify = br.readLine()) != null) {
putData = verify.replace("YYYYMMDD", yyyymmdd);
putData = putData.replace("DD", duration);
putData = putData.replace("IIIIIIIIIIIIIII", imsi);
putData = putData.replace("HHMMSS", startTime);
putData = putData.replace("hhmmss", endTime);
putData = putData.replace("XXXXXXXXX", msisdn);
putData = putData.replace("BBBBBBBBBBBBBB",
processor.returnTemplateName(template[i]));
bw.append(putData + "\n");
bsftp.append(putData + "\n");
}
}
bw.flush();
bw.close();
bsftp.flush();
bsftp.close();
br.close();
startTime = findUpdatedStartTime(startTime);
} catch (IOException e) {
e.printStackTrace();
}
}
答案 0 :(得分:1)
尝试下面给出的代码它应该可以帮助你识别页眉页脚和中间行,然后你可以随意播放并将它们写入文件中
尝试{
reader = new BufferedReader(fr);
String next, line = reader.readLine();
for (boolean first = true, last = (line == null); !last; first = false, line = next) {
last = ((next = reader.readLine()) == null);
if (first) {
header=line;
System.out.println("First Line : "+header);
} else if (last) {
footer=line;
System.out.println("Middle Line : "+footer);
} else {
middle=line;
System.out.println("Footer Line : "+middle);
}
//WriteBUlkFileWithDifferenttemplates(header,middle,footer);
}System.out.println("\n \n");
} finally {
if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
}
}