The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
January 2001



This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.


Yes, you can

Posted by Kishori Sharan on January 11, 2001 at 1:27 PM

I am making some assumptions about the posting on server done by students.
1) Student writes a program and posts the source code .java file
on server
2) Student also posts the .java file name along with the source code.
3) You want to compile that source code on server and maybe you want to show them the compiler error if any.
Once you have the source code as well as its content you can compile the code on server. YOu may want to save the source code posted by students in database or in folder as a .java file. If you save the source code in database then read the source code from database and then create a temporary file in Java. You can create a temporatry file in java using's createtempFile() method. Name this file same as the name of the class you want to compile and give extension as .java.
I have attached a sample Java program which needs to be run in order to compile the java class. I have hard coded the file name as c:\kishori\java\, you will have to read this file name.
You may want to compile all the files once all students have submitted their assignment. You can do that just reading all java files and compiling them using a loop.
If you want to trap all the errors a program compilation gave you can do that too. The sample program is doing that.

import* ;

public class Test {
public static final int a = 10 ;
public static void main ( String[] args ) throws Exception {
String[] cmd = new String[2] ;
// Full path of the javac.exe compiler
cmd[0] = "c:\\kishori\\java2\\bin\\javac.exe" ;
// Name of java file you want to compile
cmd[1] = "c:\\kishori\\java\\" ;
// Compile the file
Process p = Runtime.getRuntime().exec ( cmd ) ;
// Check for exit value
BufferedReader in = new BufferedReader ( new InputStreamReader ( p.getErrorStream ( ) )) ;

String str = null ;
// Print all the compilation error on console
while ( ( str = in.readLine() ) != null ) {
System.out.println ( str ) ;



Sponsored Links

Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us