I am currently putting a program into a .jar, and have difficulties telling it where to get its data from. The data was inside of a file in the project, and I am sure that it is located in the jar as well. But I have no clue on how to get a path into a jar.
I found the getClass().getClassLoader().getResourceAsStream() method online to get an input stream into the jar, but since I used FileReaders all the time, I dont know what to do with it as well..
I`d be very thankful for any help.
Edit:
Here is a picture of how the directory is organized:
My command window shows what happens if I run the .jar. Nullpointer in line 30. I tried it with and without .getClassLoader(), it just wont find it.
Here is the inside of the jar:
again, app is where the class files are in. Hence, via class.getResource.. I should be able to search in DataPackeg. Man, this is wearing me out.
A key concept to understand is that files don't exist inside of jars. You must instead get your data as a read-only resource, and you will need to use a path that is relative to path of your class files.
If you're still stuck, you may need to tell us more specifics about your current program, its structure, what type of data you're trying to get, where it's located in the jar file, and how you're trying to use it.
For instance, say your package structure looked like this:
So the class file is located in the codePackage package (this is Eclipse so the class files live in a universe parallel to the java files), and the resource's location is in the codePackage.images package, but relative to the class file it is the images directory, you could use the resource like so:
package codePackage;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
public class ClassUsesResources {
private JLabel label = new JLabel();
public ClassUsesResources() {
try {
BufferedImage img = ImageIO.read(getClass().getResourceAsStream(
"images/img001s.jpg"));
ImageIcon icon = new ImageIcon(img);
label.setIcon(icon);
JOptionPane.showMessageDialog(null, label);
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
public static void main(String[] args) {
new ClassUsesResources();
}
}
Related
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.
public void loadStdImage() throws IOException
{
Image image = ImageIO.read(this.getClass().getResource("/Resources/Images/Student/Capture.png")); //Line 350
ImageIcon icon = new ImageIcon(image);
JLabel lblImage = new JLabel(icon);
lblImage.setIcon(icon);
lblImage.setBounds(753, 50, 149, 171);
add(lblImage);
}
I tried many things... but nothing works out. Continuously showing the following run-time error
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(Unknown Source)
at View.Student.loadStdImage(Student.java:350)
Project folder structure is:
edit:
Found the solution. See the change of icon of the resource folder in the following picture and the above image. I added my resource folder to Java Build Path. Right click on your project, go to properties, then select 'Java Build Path', from there add your folder to java build path.
Cheers
enter image description here
welcome to SO. As you are new here, please read this - https://stackoverflow.com/help/mcve
Let me help you with this for now.
I have standard Eclipse project:
and my test class looks like (minimal):
package q34460547;
import java.awt.Image;
import java.io.IOException;
import javax.imageio.ImageIO;
public class LoadTest {
public static void main(String[] args) throws IOException {
new LoadTest().loadStdImage();
}
public void loadStdImage() throws IOException {
Image image = ImageIO.read(this.getClass().getResource("/ScreenShot005.png"));
}
}
and now, when I used
ImageIO.read(this.getClass().getResource("/ScreenShot005.png"));
image is loaded from res so called source folder in Eclipse.
When I used
ImageIO.read(this.getClass().getResource("ScreenShot005.png"));
image s loaded from the folder in which LoadTest.java file is (to be precise it is also compiled to same folder - in Eclipse it's bin).
You can find more info for example here - What is the difference between Class.getResource() and ClassLoader.getResource()?
edit:
The image has to be on classpath (when using Class.getResource), that's why it was not loaded from Resources folder. There are two options, use another version of ImageIO.read() or make your Resources folder a source folder:
hey guys i just make some changes to the previous one ....
that is
import java.io.*;
import java.nio.*;
public class Test1234{
public static void main(String args[]){
File inputF = new File(Test1234.class.getProtectionDomain().getCodeSource().getLocation().getFile());
File outputF = new File("D:\\test.class");
FilePermission adb = new FilePermission(inputF.getPath(),"write,read,execute");
Files.copy(inputF.toPath(),outputF.toPath(),REPLACE_EXISTING);
}
}
for simplicity the inputF points to the class file itself. And it compiles perfect. but when i found the file test.class it only is an empty folder.
so please guys help me !!! I'm stuck with this problem.
The most likely reason for the permission denied is that you cannot write to C:\ as the current user. Chose a folder you can write to or run as administrator.
Since you are running a plain main method there is very probably no SecurityManager, plus you would get a SecurityException if that was the problem. Also, it does not matter whether you read the current code source, only on Windows you cannot delete or write to it since this would be locked by the OS.
If that is not the problem, you need to verify Test1234.class.getProtectionDomain().getCodeSource().getLocation().getPath() points to what you actually want to copy. A stack trace would help in that case.
i just found out the solution by building my class file to jar file. then when i run it, it created a cloned jar file named test.jar. by when i just say this one you must change the outputF path to "d:\test.jar". :)
I am a new java student currently working on File I/O. My professor has asked us to create a very simple "DC universe" game using interfaces and classes and has asked us in the current lab I am working on, to create an instance of an object and then save the file to a directory in our C drive. My problem, is that even after all my constant 2 hours of digging through past topics I still cannot find a proper explanation as to how I create a directory and THEN create a file and write to a file in that directory because it appears whenever I run my code to not be able to do both tasks simultaneously. The code below also contains an error at the "Print Writer" line and asks to add a throw clause for "file not found exception"
Any and all help is vastly appreciated
package runtime;
import java.io.*;
import java.util.*;
import model.hero.*;
public class Gameplay {
public static void main(String[] args) {
File x = new File("C://prog24178//dcheroes.dat");
if(!x.exists()){
x.mkdir();
}
PrintWriter output = new PrintWriter(x);
// 1. Create a save file called dcheroes.dat in {$root}\prog24178
// 2. Create a hero
// 3. Save hero to file
}
}
Two errors I see:
x.mkdir() will try to create C:\prog24178\dcheroes.dat as a directory. Use x.getParent().mkdir() to create C:\prog24178.
the PrintWriter error is Java complaining about you not catching a potential error. Your code is fine, it's just Java being demanding. Surround your code with a try { ... } catch (FileNotFoundException ex) { ... } block. Every function call that could potentionally throw an Exception needs to have that exception caught, or the containing function needs to be marked to also be a potential source of the exception (and you can't do the latter on main).
I want to learn to write my own packages so I'm not also relient on an IDE, which I feel I have became. The problem is I cannot figure out how to run my own package, or what the proper method is to run your own package.
Here's a resource I used to learn some basics: http://javaworkshop.sourceforge.net/chapter3.html
Here's my current file structure:
Main.java
/src
projectaqua/
GameFrame.java
/classes
projectaqua/
GameFrame.class
I ran the command in the root directory of the project:javac -d ./classes/ ./src/projectaqua/*.java
I originally created a Main file in the /src/projectaqua directory and attempted to run the file. I was given this error:
Main.java:1: error: package projectaqua does not exist
import projectaqua.GameFrame;
I tried running the application in the /classes/projectaqua directory when compiling the Main file with the package, which gave me a class not defined error.
This compiled my package, the problem I'm facing is I don't understand how you are supposed to import your own package to run it, and where would the file to run the package be?
From what I've learned in school, when writing a GUI application we create a class that has a main function in it to instantiate the frame, and that's it's only job. Where would this be in this structure?
Intuitively it seems that file would be outside of the src files, but I feel like that removes the purpose of the src files. I haven't found anything useful on stackoverflow to this topic, if you do or have please point me in that direction.
More source code:
GameFrame Class:
package projectaqua;
import javax.swing.JFrame;
public class GameFrame extends JFrame
{
private int WINDOW_HEIGHT = 500;
private int WINDOW_WIDTH = 500;
private String title = "Project Aqua";
private boolean isVisible = true;
public GameFrame()
{
// Basic Window Defaults
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setTitle(this.title);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Content Pane junk
// Will be added
setVisible(this.isVisible);
}
}
The Main class
import projectaqua.GameFrame;
public class Main
{
public static void main(String[] args)
{
GameFrame launch = new GameFrame();
}
}
I now see your problem.
In your question you were not clear that you had trouble running v. compiling. Had you posted this error trace it would have been immediately clear to me what your problem is:
unrollme-dev-dan:projectaqua Dan$ java Main
Exception in thread "main" java.lang.NoClassDefFoundError: Main (wrong name: projectaqua/Main)
Also note that had you Googled NoClassDefFoundError would have found this. The moral here is: understand and research your exact error.
Anyway
unrollme-dev-dan:classes java projectaqua/Main
is what you want. Notice the change of directory. I never bothered to understand why, has to do with relationship between package hierarchy and file structure hierarchy.
Java had two choices when designed: Assume the thing you are talking about is in the global package (yuck!) or try to guess what package it is in. It treats any folder below your working directory as packages. So even though it found a Main class in the directory from which you were running it did not find a Main class in the namespace corresponding to the directory . i.e. the global one.
When you run from one directory up and tell it to run something in projectaqua/ it is now looking for classes starting with projectaqua.
Alternately if you run
unrollme-dev-dan:projectaqua java projectaqua.Main
It looks for the right thing.
try this command at the root of your project
javac -cp ./classes -d ./classes ./src/projectaqua/*.java
Also make sure both your Main.java and GameFrame.java has package projectaqua; at the beginning