Read File Present inside Java and J2EE Project

Read File Present inside Java and J2EE Project
Read File Present inside Java and J2EE Project

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:

Read File Present inside J2EE Project
Read File Present inside J2EE Project

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);
		}

Posted

in

by

Tags:


Related Posts

Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Jitendra Zaa

Subscribe now to keep reading and get access to the full archive.

Continue Reading