title: Apache POI Replace String in Word
body: <p>I've recently been working on an automated system to make and print out letters to post. The system works as follows:</p>
  
  <ul>
  <li>I create a file, with all the information in it, and replace some things with %... placeholders. For example, %name, %date, etc.</li>
  <li>When I run the application, I can select a name from the list, and it automatically loads the document, replaces all the placeholders with information supplied by a MySQL database, and prints out the document. For testing purposes, I'm just saving the document for now.</li>
  </ul>
  
  <p>I've found some tutorials on the internet, and found a code that suited my needs. Unfortunately, this code only works for Word versions older than 2007 (.doc files). What would I change for 2007+ compatibility (.docx files)?</p>
  
  <pre><code>public static void main(String[] args){
      try{
          FileInputStream fis = new FileInputStream("/Users/Jasper/Desktop/document.doc");
          POIFSFileSystem fs = new POIFSFileSystem(fis);
  
          HWPFDocument doc = new HWPFDocument(fs);
  
          Range range = doc.getRange();
          range.replaceText("%name", "Jasper");
          range.replaceText("%age", "17");
  
          FileOutputStream fos = new FileOutputStream("/Users/Jasper/Desktop/document2.doc");
          doc.write(fos);
  
          fis.close();
          fos.close();
      }catch(Exception e){
          e.printStackTrace();
      }
  }
  </code></pre>