-3

I'm trying to make a java program which executes java files and gives output in the text field. I've used Runtime class to compile the .java file .So how do I get the output from that newly made class file.

Runtime.getRuntime().exec("javac Y://CodeSave.java");
Runtime.getRuntime().exec("java Y://CodeSave.class>output.txt");
tadman
  • 194,930
  • 21
  • 217
  • 240
Akash
  • 1
  • 1
  • 1
    Dynamically compiling and executing user code is a huge security risk. May I ask why you want to do this? Perhaps there's a simpler and safer way – Sean Patrick Floyd May 02 '18 at 17:34
  • 4
    The title and body of your question do not seem to match. Are you asking how to execute a Java program and capture its output stream, from within a different Java program? – Jim Garrison May 02 '18 at 17:35
  • I was trying to add 4 other duplicates and someone reopened this. - https://stackoverflow.com/questions/11957337/read-from-another-process-output-stream –  May 02 '18 at 17:41
  • @feelingunwelcome yes, this question may be a dupe, but not of the one you linked (reading a text file) – Sean Patrick Floyd May 02 '18 at 17:45
  • I was adding 4 more about reading the outputstream of external processes, that was a copy/paste error. you need to reclose this at least with this. https://stackoverflow.com/questions/11957337/read-from-another-process-output-stream –  May 02 '18 at 18:08

2 Answers2

0

In the general case: exec returns a Process instance which has accessors (getOutputStream, etc.) for the I/O streams. You read from / write to those streams.

But: In your code you've used >output.txt. That's a shell feature. If you want to do it that way, you need to spawn a shell, not the java tool directly, and have the shell execute that command line. (A search for spawning/execing a shell should find you lots of examples.)

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
-1

Using Runtime.exec is definitely not the right way to do it, for various reasons. Examples are that both java and javac rely on environment variables which you can't pass that way.

First of all, I'd ask myself if I really needed to do this. Compiling and executing dynamically created code is a huge security risk.

But if you're sure you need to do it, here's what I'd do.

  • Move your sources to a dedicated temporary folder
  • Use the ToolProvider api to compile your sources
  • Use a dynamic throwaway ClassLoader (ByteBuddy may help you there) with a SecurityManager to load and execute your code from within your application
Sean Patrick Floyd
  • 274,607
  • 58
  • 445
  • 566