Is there a better way to do this?
I have a package with a main class called 'RainfallSeriesTranslator.bin.ui.Launcher' and some methods in a sub-directory called 'RainfallSeriesTranslator.bin.methods'. The 'methods' directory will always be in the same relative location to 'ui.Launcher', but the package could be in any location on the users machine. My intention is to develop a number of classes and to drop them into the 'methods' directory as and when, so 'Launcher' needs to be able to dynamically (or at least at compile time) list out the contents of the 'methods' directory as strings into an array called 'contents'.
My earlier attempts got it to launch from Eclipse, but not from the command prompt. I think I have traced this error to my use of the working directory as a prepend to the 'methods' directory.
The following is a successful work-around (see 'getMethods'). My idea was to get the URL of 'Launcher' as a 'bearing' and to change the relevant references to point to 'Methods'. It works for WinXP and Mac OS X.
However, it looks long-winded. Is there a better way to do it? (I have left the string manipulations uncondensed for readibility). Would this fall over on another (common) operating system?
package ui;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
public class Launcher {
private final static String name = "RainfallSeriesTranslatorPanel";
private final static String[] methods = getMethods();
private final static String fileExt = ".class";
public static void main(String[] args) {
new Panel(name, methods);
}
public static String[] getMethods() {
String fileSeparator = System.getProperty("file.separator");
//Find the URL of this class
String str1 = Launcher.class.getResource("Launcher.class").toString();
//Remove the "file:/" part of the URL
String str2 = "file:/";
String str3 = str1.replace(str2, "");
//Replace the last part of the filepath
String str4 = "ui/Launcher.class";
String str5 = "Methods";
//Assemble the absolute filepath name with system specific file separators
//Works on WinXP and Mac OS X
String str6 = str3.replace(str4, str5);
String methodDirectory = fileSeparator + str6.replace("/", fileSeparator);
File dir = new File(methodDirectory);
ArrayList <String> methodsAL = new ArrayList<String>();
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(fileExt);
}
};
String []contents = dir.list(filter);
for (int i = 0; i < contents.length; i++){
methodsAL.add(contents.replace(fileExt, ""));
};
return methodsAL.toArray(new String[methodsAL.size()]);
}
public String getPanelName() {
return name;
}
public String getFileExtensionName() {
return fileExt;
}
}PS Its curious that Mac OS X needs the absolute path to start with a file separator, but Windows seems to ignore it - possibly because it occurs before a 'C:' type of reference. I don't have an explanation, I'm just observing something that appears to work.