title: How to read and write a file in java using buffered reader and bufferedwriter
body: <p>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.</p>
  
  <pre><code>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
  </code></pre>
  
  <p>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.</p>
  
  <pre><code>My output :
  Header
  text 
  text
  Footer
  Header
  Text12
  Text12
  Footer
  
  
  
  My Code :
  
  for (int i = 0; i &lt; 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();
          }
  
      }
  </code></pre>