有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

控制台从java文件执行命令

import java.io.*;

public class chk 
{
String className;
String command,command1,command2;
public String  getMsg(String fileName,String Path) 
{
    String dir;
    command1="cd "+Path;
    dir=Path.charAt(0)+Path.charAt(1)+"";
    command2=dir;
command = "javac " + fileName;
    String a=executeCommand(command1);
    a=executeCommand(command2);
String output = executeCommand(command);
if(output.compareTo("")==0)             
        output = "Compilation Successfull!!";
    return output;
}
private String executeCommand(String command) 
{
    StringBuffer output = new StringBuffer();
    Process p;
    try 
    {
        p = Runtime.getRuntime().exec(command);
        p.waitFor();
        BufferedReader reader1 = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        BufferedReader reader2 = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = "";           
        while ((line = reader1.readLine())!= null) 
        {
            output.append(line + "\n");
        }
        while ((line = reader2.readLine())!= null) 
        {
            output.append(line + "\n");
        }
    } catch (Exception e) 
    {
        e.printStackTrace();
    }
    return output.toString();
}
public static void main(String args[])throws IOException
{
        String x;
    chk ob=new chk();
    x=ob.getMsg("MyClass.java","D:\test");
    System.out.println("OUtput : "+x);
}
}

错误

enter image description here

我试图在一个java文件的帮助下在命令提示符下运行一系列命令,以便以后我可以编译另一个名为“MyClass.java”的java文件,该文件存在于我的计算机的其他一些驱动器中,但我收到以下错误,说明它甚至无法执行我的第一个命令,即“command1=”cd“+Path;”这条线。请帮忙


共 (1) 个答案

  1. # 1 楼答案

    cd不是Windows上的程序。如果打开命令提示符窗口,将运行一个程序cmd.exe,用于输入和处理命令。许多命令会导致程序被执行,但有些命令是由cmd.exe本身解释的,包括cd命令。并且cd命令将在命令提示符窗口中设置一些状态,这些状态将影响同一cmd.exe处理未来命令的方式。因此,不仅不能将cd作为程序运行,还不能运行cmd.exe并使用它来处理cd命令。您可以,但它不会对您有任何好处,因为cd命令只会影响cmd.exe进程内发生的事情,然后cmd.exe将终止

    您可能需要研究ProcessBuilder,它有一个方法directory来设置进程的工作目录。(我对这门课不太熟悉,所以我不能给你任何具体的例子。但它看起来确实是你需要的。)

    编辑:进一步研究后:您正在使用Runtimeexec方法。exec方法的版本将工作目录作为参数:

    public Process exec(String command,
                        String[] envp,
                        File dir)
    

    因此,如果您将它与null一起用于envp(假设您不想创建一组新的环境变量),并且设置了File来引用工作目录,我认为这将满足您的需要。所以你可以用这种方式来做事情,而不是使用ProcessBuilder

    更多信息:对于类似

    java zzzzzz < C:\iptest\input.txt > C:\outtest\name.txt
    

    在命令提示符窗口中键入此命令时,cmd.exe程序将解释<>命令以重定向输入和输出,并处理所需的操作。它们在由exec()执行的命令中不起作用,因为它们只会被视为命令行参数。{}的{}方法没有设置重定向输入和输出文件的机制,但{}有。见javadoc。我对ProcessBuilder没有太多经验,但看起来需要创建一个ProcessBuilder对象,使用command设置命令和参数(作为单独的字符串,而不是带有空格字符的长字符串),使用directory设置工作目录,使用redirectInputredirectOutput设置文件重定向,然后start()