PDA

View Full Version : Running commands from a file?


uniquity
03-31-2010, 09:34 PM
For a test program I'm writing, I'm trying to have a list of commands in a .txt file so that the program can read the commands from the file and execute them. I tried looking for a suitable method in the library, mainly looking in System, Runtime, and String, but couldn't find anything that could do the job. Does anyone have any pointers on how I could do this?

Fou-Lu
04-01-2010, 03:22 PM
I don't quite follow you on this, but I kinda have an idea of what you'll be looking for. Now, I'll start off with saying I don't do enough java work, so I myself have never used this; however, I use it quite frequently with PHP. Its called Reflection, it allows you to see into classes, methods, members, etc, and often include things like the 'invoke' command to actually run something. Wait I think I've actually used this in Java once before :P
Here's a quick tutorial on reflection: http://java.sun.com/docs/books/tutorial/reflect/index.html

Also, the Class class (hah, yes its called Class) includes invokers for this as well. Using Class.forName is a great way to load classes (think.... factory for this), but to peer and execute methods you'd have to use reflection (which is ok, Class includes the getMethod(...) and getMethods() methods that returns a method) or explicitly cast. That help for what you're looking to do? I probably wouldn't recommend a file for actually executing commands or anything, but a file containing which classes to load for a factory (great for DB connections for example) would be a great idea.

brad211987
04-01-2010, 08:14 PM
You should be able to run a system command by using the Process class:


Process p = Runtime.getRuntime().exec("dir");

BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));

BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));


The buffered readers are to read the response from the command, either from std input or std error.

Of course you will need to take into account the platform you are running this on when you execute system commands.