Open and read any file in a .war file of a web application with Java | About Publisher

Open and read any file in a .war file of a web application with Java

Question: How can I open and read a file via Java inside a war file of a web application?
Answer: InputStream can be used for this with a ClassLoader.

Implementation code

For web applications, the InputStream will be created using a ClassLoader. But this approach has one limitation.
We can read only the files inside WEB-INF/classes directory.
Below is the directory structure of our web application, look at the WEB-INF/classes directory that we are going to read files from.

import java.io.InputStream;

public class WebAppFileReader {

public static void main(String[] args) throws Exception {

// Full path to file that we need to open and read
// "C://projects//myWeb//WebRoot//WEB-INF//classes//testFile.txt";
String filePath = "testFile.txt";

// InputStream inputStream = new FileInputStream(filePath);
InputStream inputStream = WebAppFileReader.class.getClassLoader()
.getResourceAsStream(filePath);

int size = 10;
byte chars[] = new byte[size];
inputStream.read(chars);

String str = "";
for (int i = 0; i < size; i++) {
str += (char) chars[i];
}
System.out.println(str);
// ....
}
}

Not standard file reading mechanims?

Reading a file via it's path is not useful with web applications (.war file) since it fails to find the files.
Even though the correct relative path is provided, programs will face issues depending on the web server versions.
Commented line above, InputStream inputStream = new FileInputStream(filePath); shows the common approach used in non-web applications. Note that only one change has to be made to make it read the files inside a web application. This is highlighted below again.

// InputStream inputStream = new FileInputStream(filePath); // #1
InputStream inputStream =
WebAppFileReader.class.getClassLoader()
.getResourceAsStream(filePath); // #2

By replacing line #1 with #2, a class to read files of a web application is created.

Note: One important point to note is: WebAppFileReader is the name of the class in which these codes will be written. So if a different class is used with these code snippet, keep in mind to alter this line and add the class name of that.

Hope this will help you.
Share this article please, on :
Share on fb Tweet Share on G+

0 Response to "Open and read any file in a .war file of a web application with Java"

Post a Comment