Last Updated: February 25, 2016
·
567
· davidecek87

Read a file in a servlet application

Preface

This is a simple way to read a file (like XML file) into a servlet application.

Requirements

  • Tomcat 7.x
  • Java J2EE (i use version 7...)

Exemple

Suppose we encode in the package farm.felix.cat and we want to read the miao.xml file (located in the same folder as our Java files).
so ...

Code

/**
 * In your method...
 */
try{
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = dbf.newDocumentBuilder();
    InputStream is = this.getClass().getResourceAsStream("/farm/felix/cat/miao.xml");

/**
 * Work with your file ;)
 */
}
catch(Exception e){
    e.printStackTrace();
}