I am learning to create game in Java and requires loading several images in before animating them. This is what I am doing now:
bg = new ImageIcon(System.getProperty("user.dir")+"/src/img/bg.jpg").getImage();
But clearly it has many disadvantages. For a start, it is long and ugly looking and I suspect, slow. Additionally, the forward slashes "/" would only work on Mac or Linux, where as on windows, it would use back slashes.
EDIT: As corrected by Samuel Rossille below, forward slash "/" in fact do work on windows.
I was wondering are there anyway of loading images, that are in the application directory, and won't be changed, in a more elegant fashion, as well as being cross-platform?
What about loading text files? Are they any different?
See the info. on embedded resources. Note that most methods & constructors that accept a File
will also accept an InputStream
or URL
. Embedded resources are read only.
On the matter of files (in the rare instance you might be using them and have to form the path from a String
).
String fileSep = System.petProperty("file.separator");
bg = new ImageIcon(System.getProperty("user.dir")+
fileSep+
"src"+
fileSep+
"img"+
fileSep+
"bg.jpg").getImage();
This is one way to get a directory path that uses the correct separator for the file-system. The File
class also offers handy constructors like new File(parent,child)
that will insert the correct separator.
As an aside, I strongly feel that all the methods & constructors in the J2SE that accept a String
intended to represent a File
path should be deprecated. If it needs a File
, give it a File
and be done with it.