如下程序是用SWT创建一个Lable和Button
用户通过点击Button然后取得要编译的Java文件的全路径
然后编译运行该文件
要编译的java程序text.java
package text;
public class text
{
  public static void main(String[] args)
  {
      System.out.println("run sccess\n");
  }
}
在E:\workspace\1\text目录下,我想问的就是在下面的程序中我们用
Process p = run.exec("java -cp E:\\workspace\\1\\ text.text")运行编译好的text.class
里面的路径是手动设置的
可不可以用exec(cmdarray,envp,dir)它代替呢??如果可以的那里面的参数要怎么设置呢?
假如我们知道的就只有用户提交的路径,那要怎么去运行编译好的文件呢??
希望高手指教啊!!!先谢谢了import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;import org.eclipse.swt.widgets.FileDialog;import org.eclipse.swt.widgets.Text;
import java.io.*;
import javax.tools.*;public class file2 
{ public static void main(String[] args) 
{
final Display display = Display.getDefault();
// 建立一个shell
final Shell shell = new Shell();
shell.setSize(500, 375);
shell.setText("SWT Application");

        //创建一个text
final Text text = new Text(shell, SWT.H_SCROLL | SWT.V_SCROLL| SWT.BORDER | SWT.WRAP);
text.setBounds(10, 66, 311, 30); // 创建一个button
final Button filedialogButton = new Button(shell, SWT.NONE);
filedialogButton.setText("浏览.....");
filedialogButton.setBounds(327, 66, 91, 30);
        
//创建按扭事件侦听
filedialogButton.addSelectionListener(new SelectionAdapter() 
{
public void widgetSelected(SelectionEvent arg0) 
{
                //OPEN式样
FileDialog fileDialog = new FileDialog(shell, SWT.OPEN);
try
{

String str = fileDialog.open();//返回最后一个选择的文件的全路径
text.append(str);
System.out.println("str:"+str);                   //编译文件
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
int results = compiler.run(System.in, System.out,System.err, str);
System.out.println((results == 0) ? "编译成功" : "编译失败");

                    //运行文件
Runtime run = Runtime.getRuntime();
Process p = run.exec("java -cp E:\\workspace\\1\\ text.text");

// 用text的输出为本程序的输入,本把该输入打印出来
InputStream br = p.getInputStream();
int s;
while ((s = br.read()) != -1) 
{
// System.out.println("555");
System.out.print((char) s);
}
}

catch (FileNotFoundException e) 
{
// TODO 自动生成 catch 块
// e.printStackTrace();
System.out.println("发射点");
} catch (Exception e) 
{
// TODO 自动生成 catch 块
     e.printStackTrace();
System.out.println("888");
}
}
});

shell.open();
shell.layout();
while (!shell.isDisposed()) 
{
if (!display.readAndDispatch())
display.sleep();
} }
}

解决方案 »

  1.   

    run.exec("java  text.text",null,new File("E:\\workspace\\1\\"))
      

  2.   

    谢谢你!!!
    不过我们从用户那就接了text.java
    的存放路径E:\workspace\1\text\text.java
    你说的那个路径E:\workspace\1\少了个个text这在里面怎么实现呢???
      

  3.   

    还想问问你中间的变量是什么意思呢??
    为什么设为null呢???
    你能解释下3个变量都是表示什么意思么???
    比如前面的命令和参数数组是怎么组合的??
    后面的路径又是指什么路径??