How to Read a File From Any Computer (Java) - java

Currently I have code like this in my program:
BufferedImage ReadPicture = null;
try {
ReadPicture = ImageIO.read(new File("C:/Users/John/Documents/NetBeansProjects/Program5/build/classes/Program5/Pictures/TestPicture.png"));
} catch (IOException e) {
}
If I compile my file to a jar and give it to someone else, the program does not work as the classpath is specific to my computer. How can I change how I access files/images so that it works on all computers?

For ImageIO in particular, if you always want to read an image from the classpath, without regard to what the classpath actually is, then you can do this:
BufferedImage readPicture = null;
URL imageUrl = getClass().getClassLoader().getResource(
"/Program5/files/Pictures/TestPicture.png");
// Or
// InputStream imageStream = getClass().getClassLoader().getResourceAsStream(
// "/Program5/files/Pictures/TestPicture.png");
// null if not found
try {
readPicture = ImageIO.read(imageUrl);
// null if the image format is unrecognized
} catch (IOException e) {
// ...
}
That relies on the fact that ImageIO can obtain images via URLs. This approach can be used even if the image is packaged in a Jar file, along side your classes (or not).

You can add a folder in your project named files or anything you want.You can make sub-directories in it and arrange files in that.They will be available when you will share it with others.In the code below,"." represents working directory.So make sure the directory structure you are providing,is correct.Try something like this.
BufferedImage ReadPicture = null;
try {
ReadPicture = ImageIO.read(new File("./files/Pictures/TestPicture.png"));
} catch (IOException e) {
}
See Also
Java Project Folder Structure

Related

Java: Read image from current src directory

I would like to load an image from my current src directory where the java class files are located as well. However, I always get an IOException..
And how can I make sure the file gets loaded properly on Mac/Linux as well on Windows?
My code so far:
String dir = System.getProperty("user.dir") + "/Logo_transparent.png";
File imageFile = new File(dir);
BufferedImage bufferedImage = null;
try {
bufferedImage = ImageIO.read(imageFile);
} catch (IOException e) {
System.out.println(e.getMessage());
System.out.println(dir);
System.out.println();
}
IOException message:
Can't read input file!
(My path is correct - is it because of the space between Google and Drive?)
/Users/myMac/Google Drive/Privat/Programming/Logo_transparent.png
Kind regards and thank you!
I think It's because you didn't create the file, You can create the file if it doesn't exist by using this code
if(!imageFile.exists()) imageFile.createNewFile();
You're code will look like this
String dir = System.getProperty("user.dir") + "/Logo_transparent.png";
File imageFile = new File(dir);
BufferedImage bufferedImage = null;
try {
if(!imageFile.exists()) imageFile.createNewFile();
bufferedImage = ImageIO.read(imageFile);
} catch (IOException e) {
System.out.println(e.getMessage());
System.out.println(dir);
System.out.println();
}
Also you shouldn't concat child files like that instead pass it as a second argument.
File imageFile = new File(System.getProperty("user.dir"), "Logo_transparent.png");
If your image files will be packaged together with your class files (for example in the same .jar) you should not use File but read it as a resource:
bufferedImage = ImageIO.read(this.getClass().getResourceAsStream("/Logo_transparent.png"));
Notice the '/' before the file name. This means to search in the root path of the classpath.
If you specify without / it will search in the package of this (the current class)
this.getClass().getResourceAsStream("Logo_transparent.png")
You can try to build the absolute path to the image like here and read it afterward.

Java BufferedImage throwing NullPointerException

I am making a space shooter in Java, but when I try to load up the image resources, I get a null pointer exception. Everything works fine except the images. Am I coding the directory wrong? How can I fix it?
Here is my code:
BufferedReader highScoreReader;
BufferedWriter highScoreWriter;
try {
playerImage = ImageIO.read(this.getClass().getResourceAsStream("src/res/player.png"));
bulletImage = ImageIO.read(this.getClass().getResourceAsStream("src/res/bullet.png"));
enemyImage = ImageIO.read(this.getClass().getResourceAsStream("src/res/enemy.png"));
highScoreReader = new BufferedReader(new FileReader("/files/HIGH_SCORE.txt"));
highScoreWriter = new BufferedWriter(new FileWriter("/files/HIGH_SCORE.txt"));
} catch (Exception e) {
e.printStackTrace();
}
Here is a screenshot of my file directories:
Most probably, you need to copy your images into the build directory of your project. If you want them treated as classpath resources, which it seems you do, make sure they're in a source folder in eclipse (or, if you use maven or similar, in the src/main/resources folder. The point is, they need to be copied to the place where the .class file lives when it's running.
Remember: class.getResourceAsStream(...) returns things from the classpath not from your source path.
I've never seen it done that way.
Try this
try {
playerImage = ImageIO.read(getClass().getClassLoader().getResourceAsStream("src/res/player.png"));
catch(IOException e) {
}
or
try {
playerImage = ImageIO.read(new File("src/res/player.png"));
catch (IOException e) {
}
Arnav Garg has discovered the problem.
When your code says something like:
file("src/res/player.png")
the file is not there, i.e.
file.exists()
will return false
Find out where java thinks the file is.
try using
file.getAbsolutePath()
and compare that to your directory structure.

Exported Jar file won't read file inside jar

In the code sample below, when I test the code in Eclipse it works just fine. However, when I export the jar file and test it via the command line, it throws an error: IIOException: Can't read input file!
private BufferedImage img = null;
private String imgSource;
if (img == null)
{
try {
URL url = getClass().getResource("Images/questionMark.png");
System.out.println(url.getPath());
/* This prints: file:/C:/Users/Keno/Documents/javaFile.jar!/javaFile/Images/questionMark.png */
File file = new File(url.getPath());
img = ImageIO.read(file);
imgSource = file.getName();
} catch (IOException e) {
e.printStackTrace();
}
}
The file I want to get is located inside the Images folder which is inside the javaFile package. I've noticed one thing that may indicate the problem.
In the print statement I have, I notice an exclamation sign at the end of the javaFile.jar section. Is that correct? Could that indicate an issue with the file or structure?
Also, just in case someone has a better suggestion as to how I should load the file, I'll tell you my intentions. I would like to load the file from a relative location (Images folder) in the jar. I would like to display it (Already done in my actual code) and also store the location to be passed later on to another function (also done).
try this
public void test() {
try(InputStream is = getClass().getResourceAsStream("Images/questionMark.png")) {
ImageIO.read(is);
} catch (IOException e) {
e.printStackTrace();
}
}
You should try to check if your class is in the same directory than Images inside your jar.
|
|- Your class
|- Images
|- questionMark.png
Also, have you tried using directly your url object ?
File file = new File(url);

Java input == null why?

I'm using a simple way to get my resources for the project. I'm using Eclipse, and I have a 'res' folder to hold the needed files. This is how I load stuff, for example a 'puppy.png' just in my res folder (no subfolders):
String path = "/puppy.png";
try {
BufferedImage image = ImageIO.read(getClass().getResourceAsStream(path));
} catch(Exception ex) { ex.printStackTrace(); }
And sometimes I get an input==null error, and sometiomes not! Not like this time puppy.png loaded but next time it won't. For some classes it always loads correctly, and for the other classes I always get this error. Can anyone explain why can this happen, and how can I fix it, but still use the getResourceAsStream() method?
Please have a look at How to retrieve image from project folder?.
I have mentioned no of ways to read image from different paths.
You can try any one
// Read from same package
ImageIO.read(getClass().getResourceAsStream("c.png"));
// Read from absolute path
ImageIO.read(new File("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\c.png"));
// Read from images folder parallel to src in your project
ImageIO.read(new File("images\\c.jpg"));
In your case the image must be in the same package where is the class and don't prefix /.
Note that if the resource returns null (meaning it doesn't exist), you will get this error.
Check the input returned like so:
String path = "/puppy.png";
try {
InputStream is = getClass().getResourceAsStream(path);
if (is == null) {
//resource doesn't exist
} else {
BufferedImage image = ImageIO.read(is);
}
} catch(Exception ex) { ex.printStackTrace(); }
Note that you most likely should be using String path = "puppy.png", seeing as you will already be in the content of the project folder.

getResourceAsStream(String) with full path returns null but file exists

Well I'm realy at a loss here. I try some JOGL and want to get a texture on an Object. I usually do it like this:
Texture[] thumbs = new Texture[pics.length];
try {
for (int i = 0; i < thumbs.length; i ++){
InputStream stream = getClass().getResourceAsStream(pics[i].getPath());
data = TextureIO.newTextureData(stream, false, "jpg");
thumbs[i] = TextureIO.newTexture(data);
}
} catch (IOException e) {
e.printStackTrace();
}
Usually this works fine if the jpg-file is in the source-directory but this time the file lies elsewhere and I recieve an IOException that says the stream was null.
pics[i].getPath() returns this String: C:\beispieluser\bjoern\eigene_bilder\eckelsheim.jpg. This is the exact path where the file lies. Can somebody tell me where my thoughts took the wrong turn?
getResourceAsStream() and friends will only open "classpath resources", which are files that appear on the classpath along with your compiled classes. To open that file, use new File() or (on Java 7) Files.newInputStream().
getResourceAsStream() finds resources that are in the classpath. I'm pretty sure it won't work for an absolute path somewhere else on your disk.
You files folder is not a part of your classpath.
You can add it, but i don't think it proper way for resources like images to be a part of classpath.
Use FileInputStream:
Code:
try{
for (int i = 0; i < thumbs.length; i ++){
File file = new File(pics[i].getPath());
FileInputStream stream = new FileInputStream(file);
data = TextureIO.newTextureData(stream, false, "jpg");
thumbs[i] = TextureIO.newTexture(data);
}
} catch (IOException e) {
e.printStackTrace();
}

Categories