Damian
Damian

Reputation: 3050

Reading from command line during execution

Is there an easy way of passing Linux/Unix commands to Java's args[] during program execution? I would like to use Java app with cron.

Upvotes: 0

Views: 191

Answers (2)

SJuan76
SJuan76

Reputation: 24895

The JVM already does that for you:

public static int main(String args[]) {...

In args[] you will have the command line arguments.

If you want more sofistication (as named parameters, v.g. -title = MyTitle), you can try Apache Command Line Interface(CLI) library.


EDIT to answer featon's comment: That will not work, the OS will interpret it as a call to launch a new process. Also, the process name of all java processes is "java" (the OS runs the JVM and does not know what it does in inside).

If what you want is to communicate with a Java process already running, you must open a communication path. Two alternatives are:

  • Open a TCP port, launch another application (Java or not) that sends the message there.
  • Have the process periodically listing a directory, if any new file appears wait a while (so it is fully created), open it, read it and delete it.

Another path is getting to use J2EE application server that implement functionalities more oriented to Java process that run continuously (even equivalents to cron tasks), but they take some effort to become familiar with.

Upvotes: 3

helios
helios

Reputation: 2821

If you have command or two pass it within String[] arguments. If you got more commands, consider putting them in some file and only pass the path to that file as a java program argument.

Upvotes: 0

Related Questions