aspose file tools*
The moose likes Java in General and the fly likes Exec'ing a string? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Exec Watch "Exec New topic
Author

Exec'ing a string?

David Duran
Ranch Hand

Joined: Feb 11, 2002
Posts: 122
Is it possible to execute a string as a line of code? For example:
String code = "System.out.println(\"Hello\");";
Java.exec(code); // == System.out.println("Hello");
Michael Morris
Ranch Hand

Joined: Jan 30, 2002
Posts: 3451
You can start a process with Runtime.getRuntime.exec("someComand") but the problem is that it has the same shell as your java program and unless you connect to its output stream and display it from the java program it just dumps its output into sort of a virtual garbage can. If the process fills the output buffer and you don't consume that output from your java program it will lock it up. Now you can use some tricks to open up a different shell, but that is platform dependent. Here's an example for Windows:
hello.bat


ProcessHelloWorld.java


Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
If you want to exectute a String as a line of Java code - well, it's possible I guess, if you surrnound it with a token class declaration, and then use exec to compile it and then run it. But I think that's going to be far too much trouble, and it probably won't work very well, and there are various complications I don't want to get into. Michael's example using shell scripting is a step in the right direction. I'd also suggest you might look into Jython, a complete scripting/programming language which can be easily invoked from Java. See this page on embedded Jython for more info.


"I'm not back." - Bill Harding, Twister
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Exec'ing a string?