Java ImageIO resource path - java

I have a Java program that runs fine in Eclipse - when I export an executable jar file it gives me an exception.
I know it is because I am giving it the wrong path but I do not know how to fix. I tried using getClass().getResourceaAsStream() (or sth. like that) but that did not work as well.
The code I am using at the moment is the following:
line 31:
BufferedImage image = ImageIO.read(new File("/src/res/loading.png"));

Okay, so I created a simple project, made a directory called res and threw some images into it
Before anyone points out that this not Eclipse, it shouldn't matter, we've already established that the Jar file contains the res directory and images, it's about replicating the structure
I then wrote a really simple example...
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
System.out.println(Test.class.getResource("/res/0.jpg"));
System.out.println(getClass().getResource("/res/0.jpg"));
}
}
which outputs...
file:/.../Test/build/classes/res/0.jpg
file:/.../Test/build/classes/res/0.jpg
No, before any points out the IDE's environment is different from the command lines, I also ran it from the command line...
java -jar Test.jar
jar:file:/.../Test/dist/Test.jar!/res/0.jpg
jar:file:/.../Test/dist/Test.jar!/res/0.jpg

Related

Icons not visible after compilation

ok i am a new one here and tried to write an awesome program:
package f;
import javax.swing.*;
public class dasMain {
public static void main(String[] args) {
ImageIcon img = new ImageIcon("pics/daFaq.png");
JOptionPane.showMessageDialog(null, img, "u r heck", JOptionPane.PLAIN_MESSAGE);
}
}
the thing is that if I run the program from Intellij Idea, then everything works fine, but after compilation the picture disappears
here are the source files of the project:
https://i.ibb.co/Njc8jYp/screen.png
i want to run this awesome code with pictures on other computers, but i only know this way and it doesn't work :(
You probably do not know where your program expects the picture to be. If you modify your code slightly, this information would be evident. Make use of
ImageIcon(URL)
File.toURI()
URI.toURL()
With that your code can look like this:
package f;
import javax.swing.*;
import java.io.File;
public class dasMain {
public static void main(String[] args) {
File png = new File("pics/daFaq.png");
System.out.println("Loading image from " + png.getAbsolutePath());
ImageIcon img = new ImageIcon(png.toURI().toURL());
JOptionPane.showMessageDialog(null, img, "u r heck", JOptionPane.PLAIN_MESSAGE);
}
}
Also I am pretty sure you intend to ship the png together with your code, so you better load it as a resource from the classpath. Here is an example.
I also investigated a bit why you would not see any error message or exception. This is documented in ImageIcon. So you might want to verify the image was loaded using getImageLoadStatus().
If you access the resource with the path like pics/file_name.png, then the pics - is the package name. And it must be located in the directory, marked as resource type. For example, create the directory, named resources in your project root, mark this directory as resource type, and move the pics there:
P. S. I would advise to use Maven or Gradle build system for managing project builds. As it is commonly accepted build management systems for the JVM projects. IDE New Project Wizard has the option to create Maven or Gradle based projects.

Error: Could not find or load main class hello.world.HelloWorld

I am trying to run this project called "hello user". I am new to Java, so wrote a simple program that takes your name, and displays "Hello ". while Running it, I get the following error:
run:
Error: Could not find or load main class hello.world.HelloWorld
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
But when I run file HelloWorld.java, it does it fine
I am doing this on Netbeans IDE 7.2
Rather than the coding error, it could be related to IDE. Since the "Run File" runs okay, but 'Run Project" does not, I believe you have something to set up in IDE itself. Right click the project, and select "Set is as Main", now run the project. I am just giving it a guess, may not help you. But it worth a shot.If it does not help, please paste your code too.
Your class needs a public static void main(String[] args) function. And moreover I suspect that the error could be in the package.
If you want your class in <main_package>.<sub_package>, The directory structure is
- main_package
- sub_package
-HelloWorld.java
And be sure to write your class like this.
package main_package.sub_package;
public class HelloWorld {
public static void main(String[] args){
System.out.println("Hello " + args[o]);
}
}
This is all due to the naming convention in Java
You need to run the .class file containing the public static void main(String[] args) method..
Here, your HelloWorld.java file might contain a class with main() method.. So, you can run it..
This is because, execution of any Java program starts with the invocation of main().. JVM needs an entry point to your code.. Which is main().. If it doesn't find one.. It will not run..
So, make sure, whatever class file you are running, it should have main() method..
UPDATE :- And for the starting point, may be you can skip using packages.. Just go with plain Java class without packages..
This message can also appear in Eclipse (Juno 4.2.2 in my case) and I have found two potential causes for it.
In my cases:
1. a DTD was in error. I deleted the file and that solved the issue*.
2. having cleaned the project, an external Jar that I had built externally had been deleted as could be seen from Properties -> Java Build Path -> Libraries.*
*Having solved either of the above issues, it was necessary to restart Eclipse
if you are using intellij idea then just rebuilding (clean and build) project might solve your problem . because intellij might be still trying to load the old classes which are not there or changed
Make sure you call looks like below:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("hello user");
}
}
To run a Java class in stand alone mode, public static void main(String[] args) is the entry method, which is must.

Java ProcessBuilder

I'm having problems using ProcessBuilder to run a class in my project.
My code:
public class Main {
public static void main(String[] args) {
try {
String pathToJar = Main.class.getProtectionDomain().getCodeSource()
.getLocation().toURI().getPath();
ArrayList<String> params = new ArrayList<String>();
params.add("javaw");
params.add("-classpath");
params.add(pathToJar);
params.add("Program");
ProcessBuilder pb = new ProcessBuilder(params);
Process process = pb.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Program is in same project (same bin folder) and works fine if ran directly but this way I get the error "Could not find the main class: Program". Where is the error in my code?
Thanks in advance.
[EDIT]
I came to the conclution that is some code on my Program class giving error. Basicly only runs with "clean" main. At eclipse, Program class is importing some libraries that are inside a jar file. Don't I need to reference it in ProcessBuilder? If so, how?
In response to your edit:
You can add the current path by switching params.add(pathToJar); with params.add(System.getProperty("java.class.path").concat(";").concat(pathToJar))‌​;.
Where is the error in my code?
(You are launching the javaw executable, so that is not the problem. It is also not that your entry point method's signature is incorrect, because that would have given a different diagnostic.)
The problem is either that the class name is incorrect (e.g. if should be "come.pkg.Program"), or the pathname for the JAR file is incorrect.
Assuming that you have eliminated the possibility that the class name is incorrect, my guess is that you are trying to use a relative pathname for the JAR file, but there is some confusion over what the current directory is; i.e. the directory in which the pathname needs to be resolved. Try using an absolute pathname in the classpath parameter.

"Selection does not contain any Java files" from eclipse

Below my Test.java which is one .java file from a student project. I don't see why eclipse gives me
" Selection does not contain any Java files " error when I tried to "run" it from the menu Run-->Run ? Could you explain why?
This post
Java launch error selection does not contain a main type
does not explain my problem. In my case "main" is well defined.
class Test {
public static void main(String[] args) {
test1();
}
static void test1() {
Font f = new Font("SansSerif", Font.PLAIN, 70);
Glyph g = new Glyph(f, 'g');
System.out.println(g);
}
}
The problem is that the file isn't in a source folder. So for Eclipse, it's just a text file which (by coincidence) contains some Java code. But since the compiler never saw it, there is no .class file -> Eclipse can't run it.
Create a source folder (New... -> Source Folder) or move the file into an existing source folder in your project (they contain a little "package" symbol in the icon) and try again.
The name of the file and the name of the class should match. That is the reason, it's not able to recognize it. Please check the name again.
Haven't used eclipse in some time now as I use InteliJ but make sure you edit configurations and select your main file so Run can then execute your app.

Using the plus sign (+) in a file path exported to a jar file

The title might not be entirely clear, but I'll try to explain.
I'm trying to access a file with a path like /net/blm50+hmm/synlist/, which works fine when I don't export to a jar file and just run it from within my IDE (eclipse). However, if I try to run it when I have exported it, I get a null pointer exception. It runs without a problem if I rename the path to not have the plus sign in it. Can I escape the plus sign or something like that?
You might ask why I don't just rename the folder, and the reason for this is laziness. There is ALOT of folders to rename and I'd rather avoid it.
I hope You can help,
shalmon
EDIT:
I have a class FileUtils I use for accessing resources in the application jar:
public class FileUtils {
public static InputStream getInputStreamForResource(String resourcePath) throws IOException {
// Try to get the file from the application jar first.
InputStream result = FileUtils.class.getResourceAsStream(resourcePath);
return result;
}
public static Scanner getScanner(String resourcePath) throws IOException {
return new Scanner(getInputStreamForResource(resourcePath));
}
}
If I call getScanner("/net/blm50+hmm/synlist/"); I get the null pointer exception.
The stacktrace is (the call to getScanner happens in NetworkCollection.fromSynapseList):
java.lang.NullPointerException
at java.io.Reader.<init>(Reader.java:61)
at java.io.InputStreamReader.<init>(InputStreamReader.java:55)
at java.util.Scanner.<init>(Scanner.java:590)
at persistence.FileUtils.getScanner(FileUtils.java:34)
at calculation.NetworkCollection.fromSynapseList(NetworkCollection.java:89)
at processes.JobDispatcher.doInBackground(JobDispatcher.java:136)
at processes.JobDispatcher.doInBackground(JobDispatcher.java:1)
at javax.swing.SwingWorker$1.call(SwingWorker.java:277)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at javax.swing.SwingWorker.run(SwingWorker.java:316)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)
For that code to work, the jar file must be available to the ClassLoader that loaded FileUtils (or simply, it should be on the classpath).
I once had a problem that could be somehow related: I got an exception when I tried to access a resource inside a jar file. Some code that worked with Java 1.4.2 but not with Java 1.6. At least I found a workaround...
Bet it's not a solution but maybe it's close enough to provide some help on your problem.
Try the following in your machine.
That is, create a file insulating the code that is failing and test it with a small subset of the input ( that is just one file, one with the + and one without it )
#create two folders: code and code+plus containing one file each
$ls -l code code+plus/
code:
total 8
-rw-r--r-- 1 oscarreyes staff 2 Jul 5 18:19 x
code+plus/:
total 8
-rw-r--r-- 1 oscarreyes staff 2 Jul 5 18:18 x
# create a sample with the code in question
$cat FileUtils.java
import java.io.*;
import java.util.*;
public class FileUtils {
public static InputStream getInputStreamForResource(String resourcePath) throws IOException {
// Try to get the file from the application jar first.
InputStream result = FileUtils.class.getResourceAsStream(resourcePath);
return result;
}
public static Scanner getScanner(String resourcePath) throws IOException {
return new Scanner(getInputStreamForResource(resourcePath));
}
public static void main( String [] args ) throws IOException {
Scanner scanner = getScanner( args[0] );
System.out.println( args[0] + " : OK");
}
}
#compile it
$javac FileUtils.java
# package it with the subfodlers
$jar -cmf mf f.jar FileUtils.class code+plus/ code
# execute it without "+"
$java -jar f.jar /code/x
/code/x : OK
#execute it with "+"
$java -jar f.jar /code+plus/x
/code+plus/x : OK
#To get Npe, use a non existing file
$java -jar f.jar /code+plus/y
Let me know if you still having the problem.
I'm pretty sure now your problem is while creating the jar file, you're now including the "+" file you think you're including.
To verify, run jar -tf your.jar and see if the file with + is listed.

Categories

Resources