Dakshila Kamalsooriya Dakshila Kamalsooriya - 3 months ago 8
Java Question

Java: Call a main method from a main method in another class

I have a set of Java files in the same package, each having main methods. I now want the main methods of each of the classes to be invoked from another class step by step. One such class file is Splitter.java. Here is its code.

public static void main(String[] args) throws IOException {

InputStream modelIn = new FileInputStream("C:\\Program Files\\Java\\jre7\\bin\\en-sent.bin");
FileInputStream fin = new FileInputStream("C:\\Users\\dell\\Desktop\\input.txt");
DataInputStream in = new DataInputStream(fin);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine = br.readLine();
System.out.println(strLine);

try {
SentenceModel model = new SentenceModel(modelIn);
SentenceDetectorME sentenceDetector = new SentenceDetectorME(model);
String sentences[] = sentenceDetector.sentDetect(strLine);

System.out.println(sentences.length);
for (int i = 0; i < sentences.length; i++) {
System.out.println(sentences[i]);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (modelIn != null) {
try {
modelIn.close();
} catch (IOException e) {
}
}
fin.close();
}
}


I now want this to be invoked in
AllMethods.java
inside a main method.
So how can I do this? There are several other class files having main methods with
IOException
which have to be invoked in
AllMethods.java
file.

Update -

I have main methods having
IOException
as well as main methods not having
IOEXception
that has to be invoked in
AllMethods.java
.

Answer

First of all, what you should probably do is refactor your code so each main method calls some other method, and then AllMethods makes calls to those new methods. I can imagine there might be some cases where it's useful if you're just trying to, for example, write some test code, but usually you wouldn't want to call main methods directly. It's just harder to read.

If you want to try it though, it's pretty easy, you just call the main method like any other static method. I once in college wrote a web server where, to handle authentication, I recursed on the main method. I think I got a C because it was unreadable code, but I had fun writing it.

class AllMethods {
    public void callsMain() {
        String[] args = new String[0];
        Splitter.main(args);
    }
}