how to call jasper report on jsp page - java

When I call the jrxml file through .load(), its throw a exception FileNotfoundException.
I have tried with absolute path, but it does not work. Please help.

FileNotFoundException generally means the file is not there. Get the path from your code and paste it in you filesystem explorer and see if it exists.
If it does, it means it is for some reason inaccessible:
This exception will be thrown by the FileInputStream, FileOutputStream, and RandomAccessFile constructors when a file with the specified pathname does not exist. It will also be thrown by these constructors if the file does exist but for some reason is inaccessible, for example when an attempt is made to open a read-only file for writing.

You should always use absolute paths in Java IO stuff. Apparently the one you tried was plain wrong. Maybe you just guessed it based on the deploy location of the webapp. You shouldn't do that. If the jrxml file is actually located in the webcontent, then you can use ServletContext#getRealPath() to convert a relative web path to an absolute disk file system path which you in turn can use further in the usual Java IO stuff.
Assuming that file.jrxml is located in webcontent root (e.g. accessible by http://example.com/contextname/file.jrxml), here's an example:
String absolutePath = getServletContext().getRealPath("file.jrxml");
File file = new File(absolutePath);

It depends on how you give it the reference to the file. Looking at the documentation for the JRXmlLoader http://jasperreports.sourceforge.net/api/net/sf/jasperreports/engine/xml/JRXmlLoader.html
you can see that you can pass it in a reference to a File object. You are probably just passing in a string and that might be wrong.
Try something like
String path = "/tmp/test.jrmxl";
File jrxmlFile = new File(path);
JasperDesign jasperDesign = JRXmlLoader.load(jrxmlFile);
with the appropriate try/catch and more and then debug on the file first before you worry about the loader.
You should probably get some of the jasperreports documentation. The books are quite good for that basic stuff.

Related

Spring does not find file in resources

i have following line
File file = ResourceUtils.getFile("classpath:calculation.csv");
and i also tried
File file = ResourceUtils.getFile("classpath:/calculation.csv");
but both will throw an error
java.io.FileNotFoundException: class path resource [calculation.csv] cannot be resolved to absolute file path because it does not exist
but i do have calculation.csv in by resources folder..
why is this?
I need to read file from resources folder, and it should also work in server enviroment
EDIT:
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("calculation.csv").getFile());
works just as fine, so not at all..
EDIT2:
tried with folder.. i have both calculation.csv and csv/calculation.csv in my resources folder now..
none of the above work, with /csv/ added.
what kind of path does this thing want?!
EDIT3:
aaand
File file = new ClassPathResource("calculation.csv").getFile();
is also no go, what even is this..
Loading file (as FILE) wont work. You must use it as resource. Files inside JAR will not work as file anyway. This is also what your "check" code shows.
classLoader.getResource("calculation.csv") works, because you are using classloader to get resource, not filesystem to get file (which is what File api does). It could work, if you would deal with non packed application. Once you pack your app into JAR, file path will be like your/path/to/jar.jar!someResource - note ! mark (and that is what you would see as well). So basicly it will return File instance, you that you wont be able to use anyway, as file system has no access to it.
You could alternatively try to extract it first with ResourceUtiuls#extractJarFileURL(URL jarUrl) and then use extracted file.
I think, that in most cases Class#getResourceAsStream is the way to go and I think that it should fit your needs as well to read content of resource.

Absolute path of a file inside a project package

I've created a file inside a project package using this code:
File xmlFile = new File("src/com/company/project/xml/tags.xml");
I am able to read the file while running from eclipse. However, after creating .jar, I'm unable to read the file. So I want to put absolute path while reading the file from the project package. How it can be done? Help and suggestions are appreciated.
In most cases, IDE's will include no Java files in the resulting Jar. Most IDE's will also include the src directory in the classpath when you run/debug the program from within them.
As a general rule of thumb, never include src in any path, src will simply not exist once the program is built.
Instead you need to make use of Class#getResource or Class#getResourceAsStream, depending on your needs. You should remember, you should never treat an "embedded" resource as a File, as in most cases it won't be, it'll be a stream of bytes in a zip file.
Something like...
URL xmlFile = getClass().getResource("/com/company/project/xml/tags.xml");
will return a URL reference to the resource. Remember, if you need a InputStream, you'll have to Class#getResourceAsStream.
If you want the resource to be writable, then you will need to find a different location to store it, as embedded resources are read only
Try with getClass().getResource()
new File(getClass().getResource("src/com/company/project/xml/tags.xml").toURI());

Instancing a java.io.File to read a resource from classpath

Supposing that I've a project structure as follows:
+ src
---+ main
------+ java
------+ resources
How can I define a java.io.File instance that is able to read an xml from resources folder?
It depends on what your program's working directory is.
You can get your working directory at runtime via System.getProperty("user.dir");
Here's a link with more info
Once you've got that, create a relative filepath pointing to your resource folder.
For example, if your working directory is src, create a relative filepath like so:
new File(Paths.get("main","resources").toString());
There are weaknesses with this approach as the actual filepath you use may change when you deploy your application, but it should get you through some simple development.
No, use an InputStream, with the path starting under resources.
InputStream in = getClass().getResourceAsStrem("/.../...");
Or an URL
URL url = getClass().getResource("/.../...");
This way, if the application is packed in a jar (case sensitive names!) it works too. The URL in that case is:
"jar:file://... .jar!/.../..."
If you need the resource as file, for instance to write to, you will need to copy the resource as initial template to some directory outside the application, like System.getProperty("user.home").
Path temp = Files.createTempFile("pref", "suffix.dat");
Files.copy(getClass().getResourceAsStream(...), temp, StandardCopyOption.REPLACE_EXISTING);
File file = temp.toFile();
As #mjaggard commented, createTempFile creates an empty file,
so Files.copy will normally fail unless with option REPLACE_EXISTING.

maven read file input from user

I am pretty new to Maven, and having some trouble reading files. Specifically, my program takes the absolute path of a file as input from the user, and then parses it. Unfortunately I am unclear on how to get my application to read a file as input from an arbitrary location.
Before I started using maven on the project, I used this code successfully:
String absolutePath = "/Users/akhalsa/path/to/file.txt";
inputStream = new BufferedReader(new FileReader(absolutePath));
However, since migrating to maven, this seems to have stopped working. From what I have read in maven I should use
InputStream in = getClass().getResourceAsStream(filePath);
Where filePath seems to be the relative path of the file in question. Does getResourceAsStream require that the file being read be inside the jar? Can this file be an external file's absolute path? When I use an absolute path here it says "Resource not found".
This must be a common problem in terms of letting users input a file from the file system for a maven application to process. What is the best way to this?
Thanks in advance.
getResourceAsStream() finds the resource on a path known to the jvm, so you can't load arbitrary files.
Maven does no magic trickery so if you are using actual absolute paths, the code should keep on working.
The "Users" part of the path reminds me of windows, but the path is not a valid windows path so are you sure you are passing along a valid absolute path?

Issues using getResource() with txt file (Java)

I have a setup in which I make use of a txt file (both reading and writing to it) in my program. At present I have it setup such that I use the local filepath on my machine, however I need to package it up into an executable JAR. To do this I've tried switching the filepath string over to the following:
String filepath = MyClass.class.getResource("/resources/textfile.txt");
However, when I run this I get a bunch of errors. After googling the method I found the similar method getResourceAsStream which I have also tried. This seems to return an InputStream object, however I need the filepath as a string ideally. Is this possible? If not what are my options?
Additional Info:
Here are the error messages I receive when trying to read & write to the txt file:
java.io.FileNotFoundException:/Users/Fred/Documents/Eclipse%20Projects/RandomProject/bin/resources/textfile.txt (No such file or directory)
Well the code you've given won't compile, because Class.getResource returns a URL, not a String. You can't treat the resource as "just another file" - because it's not.
You should basically change whatever needs to read the file to accept an InputStream instead of a filename, and then pass in the result of calling getResourceAsStream().
The method returns URL, not String. It's signature is public URL getResource(String name)
You might want to do:
String filepath = MyClass.class.getResource("/resources/textfile.txt").getPath();
I have a setup in which I make use of a txt file (both reading and writing to it) in my program.
For read only, the resource can be in a Jar on the application class-path. It is very rare (in production) for resources on the application class-path to be writable. This text file will most probably need to be put in a reproducible path (e.g. a sub-directory of user.home - where the sub-dir is based on the package name) and used as a File from that path.
Or to put that a different way. I think you are pursuing the wrong path, to achieve the goal.
If you expect to directly write to a text file inside a JAR, my friend then you are wrong all the way! Please post some more code for us to understand what is it exactly you want to achieve and how you think it could be done.

Categories

Resources