Read File in Servlets - java

I'm a beginner in Tomcat and Servlet.I come across a problem about reading File in servlet. I have search a lot information about this problem in stackoverflow,but I haven't solved it.I hope get some help.I write the code as following:
URL url=getServletContext().getResource("/WEB-INF/DataSpecification.owl");
File file=new File(url.toString());
FileInputStream input=new FileInputStream(file);
Reader in = new InputStreamReader(input,"UTF-8");
I get the following error:
java.io.FileNotFoundException: jndi:\localhost\MAGS\WEB-INF\DataSpecification.owl (File name or directory name wrong).
at java.io.FileInputStream.open(Native Method)
I put my file in WEB-INF directory.
I know that I can get an InputStream by using
getServletContext().getResourceAsStream()
But for some reasons,I nead to get a FileInputSream.
I hope to get your help!thank you!

This should work (no need to use FileInputStream):
InputStream is = getServletContext().getResourceAsStream("/WEB-INF/DataSpecification.owl");
Reader in = new BufferedReader(new InputStreamReader(is, "UTF-8"));

Related

Java Gmail API - Reading credentials from json file using Inputstream vs BufferedReader

Im trying to run my java application on Ubuntu server. I enter absolute path to read that file but it produces and error.
The code which is supposed to read that file is below.
private static final String CREDENTIALS_FILE_PATH = "/home/dockeradmin/credentials.json";
InputStream in = application.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
if (in == null) {
throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
}
And the error I get:
java.io.FileNotFoundException: Resource not found: /home/dockeradmin/credentials.json
When I tried to read file with same path using BufferedReader everything worked perfectly.
Like this:
BufferedReader br = new BufferedReader(new FileReader(new File("/home/dockeradmin/credentials.json")));
So my question is, what is the difference between these two and how could I solve my current problem?
The reason of the error is that getResourceAsStream is used to locate file on classpath and it can't be used for locating file on file system.
This line caused trouble.
InputStream in = application.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
I fixed this by replacing that, with that
InputStream in = new FileInputStream(CREDENTIALS_FILE_PATH);

How to load a File within a Jar that is not relative to the Class its loaded from

I am trying to load a file that is within a jar file. I try to get the file to load in a BufferedReader. For example:
BufferedReader br = new BufferedReader(new FileReader(fileName));
where fileName is my string from the root of the Jar file: something like this "resources/text.txt"
I am having a hard time finding out how to make this happen. Obviously FileReader will not work since it reads from the file system.
Anyone that can help me out?
Use the classloader to get the resource as a stream.
BufferedReader br = new BufferedReader(new InputStreamReader(MyClass.class.getClassLoader().getResourceAsStream("/resources/text.txt"), "utf-8");
Note that you need to specific the correct character encoding for the content.
If you are trying to access a file within the same jar as your running program you should use
final InputStream inputStream = ClassName.class.getResourceAsStream(fileName);

Reading in a file - java.io.FileNotFoundException

public void loadFile(int level){
try {
//Create new file
levelFile = new File("assets/levels.txt");
fis = new FileInputStream(levelFile);
isr = new InputStreamReader(fis);
reader = new BufferedReader(isr);
//Code to read the file goes here
Using this code, however, I keep getting the above error (java.io.FileNotFoundException).
The file definitely exists in my Assets folder and has the correct name. I've found a couple of similar questions on here and have tried various things including refreshing the project, cleaning the project, using "levels.txt" instead of "assets/levels.txt" but I keep getting this error.
Any ideas why?
Because you're dealing with outside the package, getResource() will be the best solution for your problem:
URL url = getClass().getResource("/assets/levels.txt");
File f = new File(url.toURI());
//....
Or you can directly get the input stream using getResourceAsStream() method :
InputStream is= getClass().getResourceAsStream("/assets/levels.txt");
isr = new InputStreamReader(is);
It's better since you don't have to use FileInputStream.
Note that URISyntaxException must be caught with FileNotFoundException or declared to be thrown.
In an Android project, the right way to read the content of asset files is by using the AssetManager. Asset files are the files you put in the assets/ folder of your Android project. This is mentioned briefly in the sidebar on the Accessing Resources page in the Android docs.
In particular, you can open the file assets/levels.txt and create a BufferedReader like this:
InputStream stream = context.getAssets().open("levels.txt");
BufferedReader reader = new BufferedReader(
new InputStreamReader(stream));
Notice that the argument of the open call is simply levels.txt, not assets/levels.txt.
For more details see the full docs of AssetManager.

Read file from windows directory

I tried reading xml from windows path D:/xml/xmlfile.xml
On my webpage there is a browse button. I select file and click submit. I comes to my controller and there is code to read this file.
fileToRead variable has a value = file name. Not full directory path.
InputStream ips = this.getClass().getClassLoader().getResourceAsStream(fileToRead);
InputStreamReader ipsr = new InputStreamReader(ips);
BufferedReader br=new BufferedReader(ipsr);
String line;
while ((line=br.readLine())!=null){
System.out.println(line);
}
This did not read file. Another technique also did not work and I got File not found exception
InputStream ips=new FileInputStream(file);
You can look into this site. There is working code for your problem.
http://www.codejava.net/java-ee/servlet/eclipse-file-upload-servlet-with-apache-common-file-upload
File should be on server if you want to just give file name or relative path. You have to upload file to server then read. Else you have to give full path to read file from windows directory.

Why do I get a FileNotFoundException when ClassLoader.getSystemRessource(filename) gives a result?

My current application needs to get data from a file to initialize its attributes.
It needs to be stored in a file to enable modification to the user.
String strFile = ClassLoader.getSystemResource("myFile.csv").getPath();
if(strFile==null)
throw new Exception("File not find");
BufferedReader br = new BufferedReader(new FileReader(strFile));
//Begin reading file process..
My problem is that strFile is not null but I have a java.io.FileNotFoundException when br is initialized, see the following stack:
java.io.FileNotFoundException: C:\Users\TH951S\My%20Documents\Eclipse\Workspace
\My%20App\bin\myFile.csv
(The system cannot find the path specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileReader.<init>(Unknown Source)
I checked that the file is in the designated path and everything seems correct.
Does anyone knows why this is happening? Or is there another way to get a file when the path is unknown?
Thanks for reading and more for answering,
I solve my issue, one of those that make you feel stupid for not solving it sooner.
URLs are encoding spaces with value %20 and Java do not replace the value by the space character when the FileReader is initialized. Therefore it is necessary to change %20 by " ".
There is also another way of counturning it. It is also possible to initialize the BufferedReader with an InputStreamReader as following:
InputStream in=ClassLoader.getSystemResourceAsStream("myFile.csv");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
Just for completeness: I struggled with the same problem but the result had to be a File object (because I needed the size of the file).
URL url = ClassLoader.getSystemResource("myFile.csv");
File file = new File(url.toURI());
System.out.println("Correct path: " + file.getAbsolutePath());
System.out.println("Size of file: " + file.length());
The solution is inspired by sysLoader.getResource() problem in java.
I was surprised that I had to go over so many classes but I didn't find a closer solution.

Categories