open pdf file located in a ressource folder - java

I'm trying to open a pdf located in a ressource folder with my application.
It does work on the emulator but nothing happens when I try on the exported application.
I'm guessing I'm not using the rigth path but do not see where I'm wrong. The getRessource method works very well with my images.
Here is a code snippet :
public void openPdf(String pdf){
if (Desktop.isDesktopSupported()) {
try {
URL monUrl = this.getClass().getResource(pdf);
File myFile = new File(monUrl.toURI());
Desktop.getDesktop().open(myFile);
} catch (IOException ex) {
// no application registered for PDFs
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I'm referring to the pdf variable this way : "name_of_the_file.pdf"
Edit: I've pasted the whole method

Ok, solved it. The file being located in a Jar, the only way to get it was through a inputsteam/outstream and creating a temp file.
Here is my final code, which works great :
public void openPdf(String pdf){
if (Desktop.isDesktopSupported())
{
InputStream jarPdf = getClass().getClassLoader().getResourceAsStream(pdf);
try {
File pdfTemp = new File("52502HPA3_ELECTRA_PLUS_Fra.pdf");
// Extraction du PDF qui se situe dans l'archive
FileOutputStream fos = new FileOutputStream(pdfTemp);
while (jarPdf.available() > 0) {
fos.write(jarPdf.read());
} // while (pdfInJar.available() > 0)
fos.close();
// Ouverture du PDF
Desktop.getDesktop().open(pdfTemp);
} // try
catch (IOException e) {
System.out.println("erreur : " + e);
} // catch (IOException e)
}
}

You mentioned that it is running on Emulator but not on the application. There is high probability that the platform on which the application is running does not support Desktop.
Desktop.isDesktopSupported()
might be returning false. Hence no stack trace or anything.
On Mac, you can do:
Runtime runtime = Runtime.getRuntime();
try {
String[] args = {"open", "/path/to/pdfFile"};
Process process = runtime.exec(args);
} catch (Exception e) {
Logger.getLogger(NoJavaController.class.getName()).log(Level.SEVERE, "", e);
}

Related

DLL Method Not Working After Creating Exe Of Project

I have calling display method from dll file This works when I run my java project . But it stop working after creating of project exe file. My Code is as follow ..
static {
try {
Bridge.setVerbose(true);
try {
Bridge.init();
} catch (IOException e) {
e.printStackTrace();
}
File dll_File = new File("helloworld.j4n.dll");
Bridge.LoadAndRegisterAssemblyFrom(dll_File);
helloworld.Hello.display(str)
} catch (Exception exception) {
exception.printStackTrace();
}
}
Have you signed the dll? Please sign the dll and then check.

Is this incorrect use or bad practice of class loaders?

My program is designed to launch from a runnable jar file, set everything up if needs be, and then load a class in another jar file to initiate the program. This allows for self updating, restarts, etc. Well, the class loading code I have seems a bit funky to me. Below is the code I am using to do load the program. Is this incorrect use or bad practice?
try {
Preferences.userRoot().put("clientPath", Run.class.getProtectionDomain().getCodeSource().getLocation().toURI().toString()); //Original client location; helps with restarts
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
try {
Preferences.userRoot().flush();
} catch (BackingStoreException e1) {
e1.printStackTrace();
}
File file = new File(path); // path of the jar we will be launching to initiate the program outside of the Run class
URL url = null;
try {
url = file.toURI().toURL(); // converts the file path to a url
} catch (MalformedURLException e) {
e.printStackTrace();
}
URL[] urls = new URL[] { url };
ClassLoader cl = new URLClassLoader(urls);
Class cls = null;
try {
cls = cl.loadClass("com.hexbit.EditorJ.Load"); // the class we are loading to initiate the program
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
cls.newInstance(); // starts the class that has been loaded and the program is on its way
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
The biggest problem you have is that when you get an Exception you pretend that logging the exception makes it ok to continue as if nothing happened.
If you aggregate the try/catch blocks, your code will be much shorter and easier to read, and it won't assume that exceptions don't really matter.
Try this example
public static Object load(String path, String className) {
try {
URL url = new File(path).toURI().toURL();
ClassLoader cl = new URLClassLoader(new URL[] { url });
return cl.loadClass(className).newInstance();
} catch (Exception e) {
throw new IllegalStateException("Unable to load "+className+" " + e);
}
}

Error in FileUtils.copyUrlToFile

I am executing the below code to pull the .gz file from a URL to a local directory.For small files it goes through fine but for large files it downloads only part of it but does not fail. I get to know the error only when I try to UNZIP it. Can someone throw any light on this on what could be the reason.
public boolean downloadFilemethod(String filePath, String url, String
decompressFilePath) {
if (StringUtils.isNotBlank(filePath) && StringUtils.isNotBlank(url)) {
try {
FileUtils.copyURLToFile(new URL(url), new File(SRC_BASE_DIR + filePath),
TIMEOUT_IN_MILLIS, TIMEOUT_IN_MILLIS);
ingestmethod(filePath,decompressFilePath);
downloadSuccess = true;
}
catch (MalformedURLException e)
{ LOG.warn("some message"); }
catch (IOException e)
{ LOG.warn("some message);
}
}
return downloadSuccess
}

How to open an exe file in java

I am trying to use java to open an exe file. I'm not sure which program I want to open so I am using Skype as an example. When I try to do it, it gives me errors.
try {
Process p = Runtime.getRuntime().exec("C:\\Program Files (x86)\\Skype\\Phone\\Skype");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
error:
Cannot run program "C:\Program": CreateProcess error=2, The system cannot find the file specified
Try this:
String path = "/path/to/my_app.exe";
File file = new File(path);
if (! file.exists()) {
throw new IllegalArgumentException("The file " + path + " does not exist");
}
Process p = Runtime.getRuntime().exec(file.getAbsolutePath());
You have to use a string array, change to
try {
Process p = Runtime.getRuntime().exec(new String[] {"C:\\Program Files (x86)\\Notepad++\\notepad++.exe"});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You are on windows so you have to include the extension .exe
try {
Process p = Runtime.getRuntime().exec("C:/Program Files (x86)/Skype/Phone/Skype.exe");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Maybe use File.separator instead of '\'
I tried this and it works fine, it's taken from your example. Pay attention to the double \\
public static void main(String[] args) {
try {
Process p;
p = Runtime.getRuntime().exec("C:\\Program Files\\Java\\jdk1.8.0_05\\bin\\Jconsole.exe");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

How can I create a directory in BlackBerry internal memory

I am trying to create a directory to store my application's files in the BlackBerry's internal memory. Here's the code:
String uri = "file:///store/testapp/";
FileConnection dir;
try {
dir = (FileConnection)Connector.open(uri, Connector.READ_WRITE);
if (!dir.exists()){
dir.mkdir();
}
dir.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
When I run the above I get an IOException with the message "File System Error (12)". Looking this up in the list of BlackBerry constant values this corresponds to "The operation requested is invalid.". Why can't I create the testapp directory?
You can create your own directories only in: "file:///store/home/user/"
You should only create directories in "file:///store/home/user/" or "file:///store/home/samples/" only;
For creating a directory:
public void createDirectory()
{
FileConnection file=null;
try
{
String Path="file:///store/home/user/Abc/"; // or path="file:///store/home/samples/Abc/"
file = (FileConnection)Connector.open(Path);
if(!file.exists())
file.mkdir();
file.close();
}
catch (IOException e)
{
try
{
if(file!=null)
{
file.close();
}
System.out.println("==============Exception: "+e.getMessage());
}
catch (IOException e1)
{
}
}
}
There is different in "file:///store/home/user/Abc/" and "file:///store/home/user/Abc"
If you put like "file:///store/home/user/Abc" then it take the "Abc" as file;
If you put like "file:///store/home/user/Abc/" then it take the "Abc" as directory;

Categories

Resources