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
Filewill also accept anInputStreamorURL. 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).This is one way to get a directory path that uses the correct separator for the file-system. The
Fileclass also offers handy constructors likenew 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
Stringintended to represent aFilepath should be deprecated. If it needs aFile, give it aFileand be done with it.