I'm trying to read in an html file as a string using InputStream but no matter what I try I keep getting a null pointer exception. The File I am trying to read is at "/war/index.html" and the code to read it in looks like this:
File f = new File(path);
ServletContext context = getServletContext();
InputStream is = context.getResourceAsStream(f.getAbsolutePath());
int data = is.read();
As soon as I call is.read() it gives me a NullPointerException. Any help is appreciated thanks!
Here seems to be 2 issues combined:
by default when you create file with relative path, working directory in this case is java.dir, which in most cases is not the same, as webapps folder of web-container
you seem to have extra war indicator in your path.
Please check how ServletContext resolves files.
So you simply need to use:
ServletContext context = getServletContext();
InputStream is = context.getResourceAsStream("/index.html");
Related
Always giving Inputstream is null in spring boot application for me.
Below code for getting inputstream object and image is for my resource file location.
Why I am getting inputstream object is null I am not sure.
Is there any issue I am loading this file while running power mock test case
IDataSet dataSet;
InputStream is = ClassLoader.class.getResourceAsStream("/all/testdata.json");
if (dataScript.endsWith(".json")) {
dataSet = new JsonDataSet(is);
}
Use the system classloader to access resources from the root:
ClassLoader.getSystemResourceAsStream("/all/testdata.json");
If you use:
InputStream is = YourClass.class.getResourceAsStream("/all/testdata.json");
Java looks relative to YourClass for the given file path.
If you use:
InputStream is = YourClass.class.getClassLoader().getResourceAsStream("/all/testdata.json");
Java looks relative from the root of the class path.
So I assume that you are looking for the second option
I have a war file with the below structure.
--js
--sum.js
--WEB-INF
--classes
---com
-----test
-----MyTest.class
--home.html
I am trying to read the js file in my MyTest.class file,But I am getting exception while reading it. I tried most of the solutions already mentioned in the stack.
I have tried
1)
String path = Thread.currentThread().getContextClassLoader().getResource("js/sum.js").getPath();
File f = new File(path);
System.out.println(f.getAbsolutePath());
First line is throwing nullpointer exception
2)
InputStream in =MyNashHornTest.class.getClassLoader().getResourceAsStream("/js/sum.js");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
Second line is throwing null pointer exception
3)
InputStream in =MyNashHornTest.class.getClassLoader().getResourceAsStream("../../../../js/sum.js");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
Second line is throwing null pointer exception
Please help me to resolve this issue.
For war files, don’t use the servlet container’s classloader, but use the ServletContext instead.
This method allows servlet containers to make a resource available to a servlet from any location, without using a class loader.
ServletContext context = getServletContext();
InputStream is = context.getResourceAsStream("/yourfilename.txt");
It is recommended to keep it under the /WEB-INF directory if you don’t want browers being able to access it.
The path must begin with a « / » and is interpreted as relative to the current context root. This method returns null if no resource exists at the specified path. For example ServletContext.getResourceAsStream(« WEB-INF/resources/yourfilename.cnf ») will return a nul exception, so be careful !
Why null pointer comes??
The path must begin with a "/" and is interpreted as relative to the current context root. This method returns null if no resource exists at the specified path. For example, using a path that doesn't start with a slash, You will get a null return value.
Details Description is given here: How to use ServletContext.getResourceAsStream(java.lang.String path)?
Resource Link:
HOW TO: Read a file from jar and war files (java and webapp archive) ?
You can get resources from the class path with ClassLoader.getResource or from the web root directory with ServletContext.getResource.
In a war, you use the former to access ressources stored under WEB-INF/classes, or in jars under WEB-INF/lib, and the former for what lies directly at the root of the web application.
I'm in troubles with opening file within my web-app. I tried it locally within Eclipse and it works fine but when I try to deploy it on Tomcat 6 on Openshift it doesn't find resource files for my web-app. There are some txt files in a ProjectFiles directory stored in WEB-INF directory; the code that locally opens file is
String nome_file = "C\:\\Users\\miKKo\\workspace\\fantacalcio_project\\WebContent\\WEB-INF\\ProjectFiles\\Risultati\\risultati_" + nome_lega + ".txt";
BufferedReader reader = new BufferedReader(new FileReader(nome_file));
I've pushed them within Git in the same repository (on server I renamed my project in "ROOT") and I've substituted string with this
String nome_file = this.getServletConfig().getServletContext().getContextPath()+"/WebContent/WEB-INF/ProjectFiles/Risultati/risultati_" + nome_lega + ".txt";
but it doesn't work. I've also tried with a context attribute
/var/lib/openshift/51c6178a5004467630000019/jbossews/work/Catalina/localhost/_/WEB-INF/ProjectFiles
but the thrown exception is always
java.io.FileNotFoundException: (#path) (No such file or directory)
What can I do for this?
Say your file is in the following location:
/WEB-INF/ProjectFiles/Risultati/risultat_text_file.txt
Then using:
String path = "/WEB-INF/ProjectFiles/Risultati/risultat_text_file.txt";
InputStream inputStream = new FileInputStream(this.getServletConfig().getServletContext().getRealPath(path));
Should work for you. Note that, ServletContext.getRealPath() return the real OS path corresponding to the given virtual path.
Edit:
If this doesn't work for your case, you really need to revisit your virtual path. You can manually check that does this file exist in the expected directory in the war file or you can log the output of the getRealPath() method to examine what's really going on! If necessary you can put "/" in your getRealPath() method and examine what is your application's root path.
Since I don't get application's root realpath, I resolved in this way:
String path="/WEB-INF/ProjectFiles/Risultati/risultati_test.txt";
InputStream inputStream = this.getServletConfig().getServletContext().getResourceAsStream(path);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
and now it works. By the way, I also found useful informations here
getResourceAsStream() vs FileInputStream
i know this question has been asked several times, but i think my problem differs a bit from the others:
String resourcePath = "/Path/To/Resource.jar";
File newFile = new File(resourcePath);
InputStream in1 = this.getClass().getResourceAsStream(resourcePath);
InputStream in2 = this.getClass().getClassLoader().getResourceAsStream(resourcePath);
The File-Object newFile is completely fine (the .jar file has been found and you can get its meta-data like newFile.length() etc)
On the other hand the InputStream always return null.
I know the javadoc says that the getResourceAsStream() is null if there is no resource found with this name, but the File is there! (obviously, because it's in the File-Object)
Anyone know why this happens and how i can fix it so that i can get the .jar File in the InputStream?
The getResourceAsStream() method doesn't load a file from the file system; it loads a resource from the classpath. You can use it to load, for example, a property file that's packaged inside your JAR. You cannot use it to load a file from the file system.
So, if your file resides on the file system, rather than in your JAR file, better use the FileInputStream class.
I want to read some data for my app. Here my code:
URL url = Myclass.class.getResource("/data/file.txt"); //Myclass is my class name
File file = new File(url.toString()); //maybe I met error here.
//File Constructor just receive String object, I don't know how to convert
FileInputStream reader = new FileIputStream(file);
I don't know how to change url to File to read it. Please tell me how to solve.
Thanks :)
You can't read a resource as if it were a file. The following syntax should work:
InputStream resource = MyClass.class.getResourceAsStream("/data/file.txt");
To avoid relative / absolute path issues, you can also use:
InputStream resource = MyClass.class.getClassLoader().getResourceAsStream("/data/file.txt");