[英]How to read and write a file in java using buffered reader and bufferedwriter
I need to read a file and write into a separate file. 我需要读取一个文件并将其写入一个单独的文件。 I must also be able to read two files and write them into a single file.
我还必须能够读取两个文件并将它们写入单个文件。
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
the first line and last line remains same but only the middle lines are appended. 第一行和最后一行保持不变,但仅附加中间行。 According to my code.
根据我的代码。 The header and footer is appended twice.
页眉和页脚被附加两次。
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();
}
}
Try the code given below it should help you to identify header footer and middle lines, then u can play around and write them into a file as u wish 试试下面给出的代码,它应该可以帮助您识别页眉页脚和中间行,然后您可以随意播放并将它们写入文件中
try { 尝试{
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) {}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.