In My Java app, i have structure like this,
sip
build
dist
nbproject
src
sip
Form.java
schedule.jrxml
test
And this my code to load jrxml in Form.java
try{
//String schedule_all ="E:\\My Data\\Tugas Akhir\\repos\\sip\\src\\sip\\jadwal.jrxml";
InputStream file = this.getClass().getClassLoader().getResourceAsStream("/sip/schedule.jrxml");
JasperReport jr= JasperCompileManager.compileReport(file);
JasperPrint jp = JasperFillManager.fillReport(jr, null,con);
JasperViewer jv = new JasperViewer(jp,false);
jv.setVisible(true);
}
catch(Exception e){
JOptionPane.showMessageDialog(null,"Error show Document");
tambah_log(e.toString());
}
I Want to replace this path(E:\My Data\Tugas Akhir\repos\sip\src\sip\jadwal.jrxml";)
to my local project path like this ("/sip/jadwal.jrxml").
but i got this error
net.sf.jasperreports.engine.JRException:
java.net.MalformedURLException
Any Idea? Because i want deploy my system to another computer. And i wont configure its path again.
FIXED
I change My Code like this.
InputStream file = this.getClass().getClassLoader().getResourceAsStream("/sip/jadwal.jrxml");
JasperReport jr= JasperCompileManager.compileReport(System.getProperties().getProperty("java.class.path").split(";")[System.getProperties().getProperty("java.class.path").split(";").length - 1]+"\\sip\\jadwal.jrxml");
JasperPrint jp = JasperFillManager.fillReport(jr, null,con);
JasperViewer jv = new JasperViewer(jp,false);
jv.setVisible(true);
Your getResourceAsStream("/sip/schedule.jrxml"); call doesn't accept that type of "URL"
Check the documentation, if its a local file it probably wants "file:///C:/path/to/whereever/sip/schedule.jrxml"
Or you could see the solution posted here: https://community.oracle.com/thread/620656?start=0&tstart=0
Or better yet here
http://forum.spring.io/forum/spring-projects/container/62863-how-to-use-getresourceasstream-to-get-a-file-stream
In windows operating systems java accepts the drive having the os installation as root directory. If you put your /sip directory to that drive, for example (and generally) to C drive. Then you can reach it as
this.getClass().getClassLoader().getResourceAsStream("/sip/schedule.jrxml"); .
Putting the schedule.jrxml to a package or to a resource folder of the project is a better practice though, because in this case you may install it anywhere you want.
Related
I am trying to convert video to audio . That is why , I am using the following code :
File source = new File("E:\\Shunno - Khachar Bhitor Ochin Pakhi.mp4");
File target = new File("E:\\output.mp3");
AudioAttributes audio = new AudioAttributes();
audio.setCodec("libmp3lame");
audio.setBitRate(new Integer(128000));
audio.setChannels(new Integer(2));
audio.setSamplingRate(new Integer(44100));
EncodingAttributes attrs = new EncodingAttributes();
attrs.setFormat("mp3");
attrs.setAudioAttributes(audio);
Encoder encoder = new Encoder();
try
{
encoder.encode(source, target, attrs);
}
catch (IllegalArgumentException | EncoderException e)
{
}
But I am getting the following error :
Sep 26, 2016 11:28:29 AM it.sauronsoftware.jave.DefaultFFMPEGLocator copyFile
SEVERE: Could not get native library for ffmpeg-amd64.exe
Exception in thread "main" java.lang.RuntimeException: Cannot retrieve native file ffmpeg-amd64.exe
at it.sauronsoftware.jave.DefaultFFMPEGLocator.copyFile(DefaultFFMPEGLocator.java:139)
at it.sauronsoftware.jave.DefaultFFMPEGLocator.<init>(DefaultFFMPEGLocator.java:80)
at it.sauronsoftware.jave.Encoder.<init>(Encoder.java:105)
at Convert.main(Convert.java:29)
How can I solve this error ? Please help me .
The error is very clear: ffmpeg cannot been found.
Since you hard coded some windows path here is the windows binary of ffmpeg. I suggest to download the x64 static version. Since that is just one file you need to care about.
If you need it for another platform check the download site.
Within the zip file in the subdirectory bin where the binary ffmpeg.exe is located. Now you need to renamed it to ffmpeg-amd64.exe since the library expects that name. Now you need to copy the file to a directory of your path variable e.g. C:\windows\system32. I suggest not to use that directory, but this is the simplest way. Better put it somewhere else and modify your path variable. There are dozens of explanations so just google them if you want how do achieve that.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have written the following code for creating jasper report, this code working fine in NetBeans IDE, but after creating jar file of that project the report is not opening. Its also not showing any error.
What can be the issue?
Code for creating jasper report
//Path to your .jasper file in your package
String reportSource = "src/report/Allvendor_personal_info.jrxml";
try
{
jasperReport = (JasperReport)
JasperCompileManager.compileReport(reportSource);
jasperPrint = JasperFillManager.fillReport(jasperReport, null, con);
//view report to UI
JasperViewer.viewReport(jasperPrint, false);
con.close();
}
catch(Exception e)
{
JOptionPane.showMessaxgeDialog(null, "Error in genrating report");
}
The path src will not exist at runtime and you should never reference it.
Based on this, the Allvendor_personal_info.jrxml will be an embedded resource, stored within the Jar file, you won't be able to access it like you do normal files, instead, you need to use Class#getResource or Class#getResourceAsStream
String reportSource = "/report/Allvendor_personal_info.jrxml";
InputStream is = null;
try
{
is = getClass().getResourceAsStream(reportSource);
jasperReport = (JasperReport)JasperCompileManager.compileReport(is);
jasperPrint = JasperFillManager.fillReport(jasperReport, null, con);
//...
} finally {
try {
is.close();
} catch (Exception exp) {
}
}
Now, having said that, there should be very little reason to ever compile a .jrxml file at runtime, instead, you should compile these files at build time and deploy the .jasper files instead. This will improve the performance of your application as the complication process is not short even for a basic report.
This would mean you would use...
jasperReport = (JasperReport) JRLoader.loadObjectFromFile(is);
Instead of JasperCompileManager.compileReport
Set environment variables to lib folder of jar files
Well guys, I don't know if It's too late, but I wasted 1 day searching the solutions to this problem, about JasperReport after building an Jar executable. To get your Reports working after building a jar, you just need to write the following lines
String reportUrl = "/reports/billCopyReport.jasper"; //path of your report source.
InputStream reportFile = null;
reportFile = getClass().getResourceAsStream(reportUrl);
Map data = new HashMap(); //In case your report need predefined parameters you'll need to fill this Map
JasperPrint print = JasperFillManager.fillReport(reportFile, data, conection);
JasperViewer Jviewer = new JasperViewer(print, false);
Jviewer.setVisible(true);
/* var conection is a Connection type to let JasperReport connecto to Database, in case you won't use DataBase as DataSource, you should create a EmptyDataSource var*/
you need to copy folder which has jasper/Jrxml files and put it same directory of your jar file.
whenever you write code like this
String reportSource = "/report/Allvendor_personal_info.jrxml";
//It will look for this file on your location so you need to copy your file on /report/ this location
InputStream is = null;
try
{
is = getClass().getResourceAsStream(reportSource);
jasperReport = (JasperReport)JasperCompileManager.compileReport(is);
jasperPrint = JasperFillManager.fillReport(jasperReport, null, con);
//...
} catch(Exception e){
}
I am creating Jasper reports from My Java Web Application through a pre-designed Jrxml file. the file is in My web folder (Netbeans) in a directory named jrxml so I am trying to get at it using this Method.
public void generateChurchReport(IncomeExpenseBean ieb) {
church = ieb.getChurch();
user = ieb.getUser();
String currdate = dt.getCurrentDate();
Connection conn = db.getDbConnection();
Map parameters = new HashMap();
try{
parameters.put("ChurchName", church);
JasperReport jasperReport = JasperCompileManager.compileReport("/jrxml/ChurchIncome_expenseReport.jrxml");
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, conn);
File f = new File(user + church+ currdate + ".pdf");
JasperExportManager.exportReportToPdfFile(jasperPrint, f.getAbsolutePath());
Desktop.getDesktop().open(new File(f.getAbsolutePath()));
}catch(Exception asd){
System.out.println(asd.getMessage());
}
}
I am getting File Not Found Exception because the Application is expecting the file somewhere in ;
C:\Program Files\glassfish-3.1.2.2\glassfish\domains\TestDom\jrxml\
How do i read this file in my web folder and How can I create the Reports Inside the same folder?
EDIT If I do not give Any Paths My reports are getting Generated at C:\Program Files\glassfish-3.1.2.2\glassfish\domains\TestDom\ if the jrxml file is in that Location.
What you are doing wrong here is, you are trying to locate your jrxml file somewhere in web folder from your java class. This will definitely raise "File Not found error" at run time because of incorrect context path. You could simply do the following:-
Make a folder named say "Jrxml" under your java classes package. Suppose java classes package is com.ejb.beans, make a folder com.ejb.beans.jrxml.
Put all your jrxml files into this folder.
In your java class, load the class loader and locate the jrxml by its name and you will easily access it. Here is the code:-
ClassLoader classLoader = getClass().getClassLoader();
InputStream url = null;
url = classLoader.getResourceAsStream("Report.jrxml");
This url can be used to compile report as :-
JasperReport jasperReport = JasperCompileManager.compileReport(url);
To create the report output file, you could store it at some path in your application server. Set your server path in environment variable and extract it in your class at runtime like this :-
String serverHomeDir = System.getProperty("server.home.dir");
String reportDestination = serverHomeDir + "/domains/ReportOutput/report.html";
// now print report at reportDestination
JasperExportManager.exportReportToHtmlFile(jasperPrint, reportDestination);
Your html file will be generated at the required destination, which you can easily read and render it, the way you want to, through your web page.
I have this strange thing with input and output streams, whitch I just can't understand.
I use inputstream to read properties file from resources like this:
Properties prop = new Properties();
InputStream in = getClass().getResourceAsStream( "/resources/SQL.properties" );
rop.load(in);
return prop;
It finds my file and reds it succesfully. I try to write modificated settings like this:
prop.store(new FileOutputStream( "/resources/SQL.properties" ), null);
And I getting strange error from storing:
java.io.FileNotFoundException: \resources\SQL.properties (The system cannot find the path specified)
So why path to properties are changed? How to fix this?
I am using Netbeans on Windows
The problem is that getResourceAsStream() is resolving the path you give it relative to the classpath, while new FileOutputStream() creates the file directly in the filesystem. They have different starting points for the path.
In general you cannot write back to the source location from which a resource was loaded, as it may not exist in the filesystem at all. It may be in a jar file, for instance, and the JVM will not update the jar file.
May be it works
try
{
java.net.URL url = this.getClass().getResource("/resources/SQL.properties");
java.io.FileInputStream pin = new java.io.FileInputStream(url.getFile());
java.util.Properties props = new java.util.Properties();
props.load(pin);
}
catch(Exception ex)
{
ex.printStackTrace();
}
and check the below url
getResourceAsStream() vs FileInputStream
Please see this question: How can I save a file to the class path
And this answer https://stackoverflow.com/a/4714719/239168
In summary: you can't always trivially save back a file your read from the classpath (e.g. a file in a
jar)
However if it was indeed just a file on the classpath, the above answer has a nice approach
I have deployed my app to jar file. When I need to copy data from one file of resource to outside of jar file, I do this code:
URL resourceUrl = getClass().getResource("/resource/data.sav");
File src = new File(resourceUrl.toURI()); //ERROR HERE
File dst = new File(CurrentPath()+"data.sav"); //CurrentPath: path of jar file don't include jar file name
FileInputStream in = new FileInputStream(src);
FileOutputStream out = new FileOutputStream(dst);
// some excute code here
The error I have met is: URI is not hierarchical. this error I don't meet when run in IDE.
If I change above code as some help on other post on StackOverFlow:
InputStream in = Model.class.getClassLoader().getResourceAsStream("/resource/data.sav");
File dst = new File(CurrentPath() + "data.sav");
FileOutputStream out = new FileOutputStream(dst);
//....
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) { //NULL POINTER EXCEPTION
//....
}
You cannot do this
File src = new File(resourceUrl.toURI()); //ERROR HERE
it is not a file!
When you run from the ide you don't have any error, because you don't run a jar file. In the IDE classes and resources are extracted on the file system.
But you can open an InputStream in this way:
InputStream in = Model.class.getClassLoader().getResourceAsStream("/data.sav");
Remove "/resource". Generally the IDEs separates on file system classes and resources. But when the jar is created they are put all together. So the folder level "/resource" is used only for classes and resources separation.
When you get a resource from classloader you have to specify the path that the resource has inside the jar, that is the real package hierarchy.
If for some reason you really need to create a java.io.File object to point to a resource inside of a Jar file, the answer is here: https://stackoverflow.com/a/27149287/155167
File f = new File(getClass().getResource("/MyResource").toExternalForm());
Here is a solution for Eclipse RCP / Plugin developers:
Bundle bundle = Platform.getBundle("resource_from_some_plugin");
URL fileURL = bundle.getEntry("files/test.txt");
File file = null;
try {
URL resolvedFileURL = FileLocator.toFileURL(fileURL);
// We need to use the 3-arg constructor of URI in order to properly escape file system chars
URI resolvedURI = new URI(resolvedFileURL.getProtocol(), resolvedFileURL.getPath(), null);
File file = new File(resolvedURI);
} catch (URISyntaxException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
It's very important to use FileLocator.toFileURL(fileURL) rather than resolve(fileURL)
, cause when the plugin is packed into a jar this will cause Eclipse to create an unpacked version in a temporary location so that the object can be accessed using File. For instance, I guess Lars Vogel has an error in his article - http://blog.vogella.com/2010/07/06/reading-resources-from-plugin/
I got a similiar issues before, and I used the code:
new File(new URI(url.toString().replace(" ","%20")).getSchemeSpecificPart());
instead of the code :
new File(new URI(url.toURI())
to solve the problem
While I stumbled upon this problem myself I'd like to add another option (to the otherwise perfect explanation from #dash1e):
Export the plugin as a folder (not a jar) by adding:
Eclipse-BundleShape: dir
to your MANIFEST.MF.
At least when you export your RCP app with the export wizard (based on a *.product) file this gets respected and will produce a folder.
In addition to the general answers, you can get "URI is not hierarchical" from Unitils library attempting to load a dataset off a .jar file. It may happen when you keep datasets in one maven submodule, but actual tests in another.
There is even a bug UNI-197 filed.