Consider above project hierarchy, we want to read the file “hibernate.cfg.xml” in “TestMain.java”. If we try to get the absolute path using “(new File(“”)).getAbsolutePath()“ then it will give the path of eclipse in case we are using eclipse or tomcat from where the application is running. This problem occurs mainly in file upload functionality.
Below code can be used to solve this type of problem.
package com.G2.servlets; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; public class TestMain { /** * @param args */ public static void main(String[] args) throws Exception { TestMain testMain = new TestMain(); InputStream st = testMain.getClass().getResourceAsStream("/hibernate.cfg.xml"); BufferedReader in = new BufferedReader(new InputStreamReader(st)); String line; while((line = in.readLine()) != null) { System.out.println(line); } } }
Now consider below situation:
You need to read the file present in folder “WebContent”. To read the file, we can use here Servlet Context.
InputStream st= getServletContext().getResourceAsStream("/css/style.css"); BufferedReader in = new BufferedReader(new InputStreamReader(st)); String line; while((line = in.readLine()) != null) { System.out.println(line); }
Leave a Reply