I'm currently working on a program for random play of my MediaPlayList (Simpsons, Futurama, Music etc.). Therefore i wrote a subroutine, which is finding and filtering
all media files in a given folder:
This routine is taking every file which isn't .jpg or .cmd at the moment. Works, everything fine. (Perhaps you have an idea of how to make thisroutine smaller and perhaps nonrecursive oO ?)
Now, i want to filter things explicitly by their filetype, and I don't want to do it in the manner done here (with if(path not contains bla)) but with a method of file like f.isMediaFile().
I therefore wrote a MediaFile Class:
and changed the type of my get the files routine to
but now, I get a classcast error (Exception in thread "main" java.lang.ClassCastException: [Ljava.io.File; cannot be cast to [LMediaFile;) on:
direc is of type MediaFile, but will return a File Array. Where is my error in this concept, how can I circumvent this? Everthing I want is the easier checking if a File is a Media-File or not.
Override listFiles (all 3 of them) to convert the File into a MediaFile:
Since the other listFiles methods will require a lot of the same code you should add a private method for converting a File into a MediaFile.
However, I don't like this idea. Your MediaFile class exists only to make it easier for you to filter out non-media files. listFiles() already has support for that, using FileFilter and FilenameFilter. For instance:
Now List (bad name by the way, it should start with a lowercase L) will only contain File objects which are either directories or files that contain .jpg in the name but not .cmd.
A thing in my mind, and with the code posted above I hope its resonable to post it here, is: Is it neccesary to count all the files first, then create the File-Array, and after that, filling it with all the files? It seems to me rather complicated. Isn't there an easier way?
Thorsten Jaeger wrote:A thing in my mind, and with the code posted above I hope its resonable to post it here, is: Is it neccesary to count all the files first, then create the File-Array, and after that, filling it with all the files? It seems to me rather complicated. Isn't there an easier way?
The easier way would be to use a List (e.g. ArrayList) instead of an array. Then you don't need to know how big it is in advance - you can just add files to it as necessary.