问题
I have been trying to create an image object like this:
Image img = new Image("images/jack.png");
or
Image img = new Image("jack.png");
or /jack.png
or /images/jack.png
etc.
I have looked up the working directory using System.getProperty("user.dir")
and it is indeed where I put my image file. When I use file:
prefix, it does work, like so:
Image img = new Image("file:images/jack.png");
However, it is also supposed to work without using it. In the textbook it is done without file:
. I've seen other codes that work without it.
At the end of a bunch of chained exceptions, it says:
Caused by: java.lang.IllegalArgumentException: Invalid URL or resource not found
I also tried to read source code from OpenJDK
and I could figure anything out because many methods were native and from what I traced I didn't understand how it didn't work. Also, I can create files the same way, I just can't create images. For instance, this works:
File file = new File("fileName.txt");
What causes this problem, what should I do to fix it?
I'm using NetBeans, if that matters.
回答1:
Note that System.getProperty("user.dir")
does not return the working directory. It returns the user directory.
A path relative to the working directory can be specified using a relative file path in the File
constructor. However it's bad practice to rely on the working directory. Starting the application from NetBeans results in the working directory being the project directory, but this is not the case, If started in a different way.
Images you need in your application should therefore be added to the jar.
In this case you can retrieve the image URL
via Class.getResource(). (convert to String
using toExternalForm()
.)
If you have a File
that references a image file, you can use the File
instance to get a URL
:
File file = ...
String urlString = file.toURI().toURL().toExternalForm();
Those URLs can be used with the Image
constructor.
Note that
File file = new File("fileName.txt");
does not create a file. It just represents a file path. This file may or may not exist. Simply invoking the File
constructor does not create a new one.
回答2:
File file = new File("name.txt");
creates a file somewhere. It doesn't read the existing file whereas
Image image = new Image("pathToImage.png");
tries to read the existing image. In order to be able to read an image stored somewhere you need either the absolute path, which requires the protocol (http
, file
, ftp
etc.) or you put your image into the 'known' directory, like the resources dir of your project.
Say, you have your java sources under src/main/java
. The resources dir could be src/main/resources
. Put your image there and try working with relative path relative to src/main/resources
.
来源:https://stackoverflow.com/questions/39609896/cannot-construct-an-image-object-with-relative-file-path-without-using-file-pre