I am not able load image using getClassLoader Method - java

Below is the code that I am trying to use.
InputStream in = new BufferedInputStream(Tester.class.getClassLoader().getResourceAsStream("appResources/img/GESS.png"));
Image image=null;
try {
image = ImageIO.read(in);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(image);
'image' comes null when I am printing it.

Try this:
InputStream in = Tester.class.getResourceAsStream("your/path");
Image image=null;
try {
image = ImageIO.read(in);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(image);
The value or your/path is either appResources/img/GESS.png or /appResources/img/GESS.png depending on your maven configuration and the directory you setup for your project.
For instance, if you add the following entry to your pom.xml file:
<resources>
<resource>
<directory>src/main/appResources</directory>
</resource>
</resources>
Then, you can get the same resource by using a shorter path since your program knows where to look for resources:
InputStream in = Tester.class.getResourceAsStream("img/GESS.png");
Image image=null;
try {
image = ImageIO.read(in);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(image);
More info here and here.

you can use InputStream instream=Thread.currentThread().getContextClassLoader().getResourceAsStream("appResources/img/GESS.png");

you use like this
InputStream instream=Thread.currentThread().getContextClassLoader().getResourceAsStream("appResources/img/GESS.png");

Here are two utility methods I'm using for image loading.
public static Image getImage(final String pathAndFileName) {
try {
return Toolkit.getDefaultToolkit().getImage(getURL(pathAndFileName));
} catch (final Exception e) {
//logger.error(e);
return null;
}
}
public static URL getURL(final String pathAndFileName) {
return Thread.currentThread().getContextClassLoader().getResource(pathAndFileName);
}

Related

How to solve Function1 (Context) in Function1 cannot be applied to ()

I have the following problems:
I would like to call a function from another class so I added this line of code
Function1 func = new Function1(); and I get an error saying
Function1 (Context) in Function1 cannot be applied to ()
Furthermore, relating to this function and its error, I intend calling the aforementioned function which takes a JSON object and a Filename as parameters and it returns a file, however, when I enter it, I get the following error
Wrong 2nd argument type, found Java.lang.String required Java.io.File
The code in question is this:
JSONObject export = jsonArray1.getJSONObject(index);
File file = func.exportToFile(export, "Export.json");
The fuction in question starts like this:
public void exportToFile(JSONObject objectToExport, File fN)
{
String output = objectToExport.toString();
file_ = fN;
if (!file_.exists()) {
try {
file_.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try{
FileOutputStream fOut = new FileOutputStream(file_);
fOut.write(output.getBytes());
fOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
N.B.: I have tried to call the function like this:
File file = func.exportToFile(export, func.file);
but I only get the error saying incompatible types
Required Java.io.file
Found Void
What have I done wrong?
this func.exportToFile(export, func.file); will not return anything since exportToFile it's a void method .
change your method to make it return file this way :
public File exportToFile(JSONObject objectToExport, File fN) {
String output = objectToExport.toString();
file_ = fN;
if (!file_.exists()) {
try {
file_.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try{
FileOutputStream fOut = new FileOutputStream(file_);
fOut.write(output.getBytes());
fOut.close();
return file_;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

get the sharedlink of an existing file in Dropbox using the dropBox-sdk-java

I want to retrieve the shared file url of an existing file on Dropbox. I am using the dropbox-java-sdk, and I have managed to create a shared link for a file I just uploaded. The only way I managed to get the shared link of an existing file is by listing all links and get the one I want depending on the path, like so
public void getShareLink(String path) throws DbxApiException, DbxException{
DbxRequestConfig config = new DbxRequestConfig("test/DbApi-sdk");
DbxClientV2 client = new DbxClientV2(config, getToken(AuthorizationFile));
try {
ListSharedLinksResult sharedLinkMetadata = client.sharing().listSharedLinks();
for (SharedLinkMetadata slm: sharedLinkMetadata.getLinks()){
if(slm.getPathLower().equalsIgnoreCase(path)){
System.out.println(slm.getUrl());
return;
}
}
} catch (CreateSharedLinkWithSettingsErrorException ex) {
System.out.println(ex);
} catch (DbxException ex) {
System.out.println(ex);
}
}
Isn’t there a way to directly get the url for the file I want? I just think it is a waste to iterate all items just to get one of them.
Get a ListSharedLinksBuilder from listSharedLinksBuilder and set ListSharedLinksBuilder.withDirectOnly to request only links for the exact path specified:
public String getShareLink(String path) {
DbxRequestConfig config = new DbxRequestConfig("test/DbApi-sdk");
DbxClientV2 client = new DbxClientV2(config, getToken(AuthorizationFile));
try {
ListSharedLinksResult sh = client.sharing().listSharedLinksBuilder()
.withPath(path)
.withDirectOnly(true)
.start();
for (SharedLinkMetadata slm : sh.getLinks()) {
return slm.getUrl();
}
} catch (CreateSharedLinkWithSettingsErrorException ex) {
System.out.println(ex);
return null;
} catch (DbxException ex) {
System.out.println(ex);
return null;
}
return null;
}

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);
}
}

open pdf file located in a ressource folder

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);
}

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