通过在java中模拟命令shell如何执行文件?

时间:2014-09-18 17:48:47

标签: java shell cmd command

我创建了一个模拟命令shell(cmd)的程序,它的工作方式和我使用线程一样完美,因此用户可以在不阻塞shell的情况下编写新命令。

但是,现在iam尝试创建命令(Showerrlog),每当用户键入此命令时,他应该能够看到他或她在上一个会话期间尝试执行的错误命令。

用于执行iam使用(文件处理程序),它将在每个新会话中创建一个新的.log文件。但是,不幸的是,我仍然无法打开包含错误命令的最后一个日志文件。我不知道为什么!!

请查看我的代码,随时纠正我:

package witheyul;

import static com.sun.corba.se.impl.util.Utility.printStackTrace;
import com.sun.javafx.tk.FileChooserType;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import static java.lang.Compiler.command;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.function.Supplier;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import java.lang.Runtime;
import java.util.concurrent.Executors;
import sun.awt.shell.ShellFolder;

/**
 *
 * @author ad
 */
public class WithEyul implements Runnable {
    int x = 0;
    String command;
    public WithEyul(String command){
        this.command = command;
    }

    @Override

    public void run(){
          List<String> input = new ArrayList<String>();
        StringTokenizer tokenizer = new StringTokenizer(command);
        while (tokenizer.hasMoreTokens()) {
            input.add(tokenizer.nextToken());
        }
        ProcessBuilder pb = new ProcessBuilder(input);
        // ProcessBuilder creates a process corresponding to the input command
        // now start the process
        BufferedReader br = null;
        try {
            Process proc = pb.start();
            // obtain the input and output streams
            InputStream is = proc.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            br = new BufferedReader(isr);
            // read what the process returned
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
            br.close();
        } catch (java.io.IOException ioe) {


              try {
                  System.err.println("Error");


                  // try {
                  Logger logger = Logger.getLogger("Testing");
                  FileHandler fh;
                  fh = new FileHandler("E:/MyLogFile.log");
                  logger.addHandler(fh);
                  SimpleFormatter formatter = new SimpleFormatter();
                  fh.setFormatter(formatter);
                  logger.info(command);
                     }
                    catch (SecurityException e){
                  printStackTrace();

                  while (command.equalsIgnoreCase("Showerrlog")){
                      try {

                          Runtime.getRuntime().exec("E:\\MyLogFile.log");

                      } catch (IOException ex) {
                          Logger.getLogger(WithEyul.class.getName()).log(Level.SEVERE, null, ex);
                      }
                  }

              } catch (IOException ex) {
                  Logger.getLogger(WithEyul.class.getName()).log(Level.SEVERE, null, ex);
              }
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException ex) {
                    Logger.getLogger(WithEyul.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

        }



    }

    }

这里是主要的方法类:

package witheyul;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

/**
 *
 * @author ad
 */
public class TestProcessBuilder {

    static void createProcess(String command) throws java.io.IOException {
      Thread t = new Thread (new WithEyul(command));
      t.start();

        }

      public static void main(String[] args) throws java.io.IOException {

        String commandLine;
        File wd;
        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("\n\n***** Welcome to the Java Command Shell *****");
        System.out.println("If you want to exit the shell, type END and press RETURN.\n");
        // we break out with ‘END’
        while (true) {
            // show the Java shell prompt and read what command they entered
            System.out.print("jsh>");
            commandLine = console.readLine();
            // if user entered a return, just loop again
            if (commandLine.equals("")) {
                continue;
            }
            if (commandLine.toLowerCase().equals("end")) { //User wants to end shell
                System.out.println("\n***** Command Shell Terminated. See you next time. BYE for now. *****\n");
                System.exit(0);
            }

            createProcess(commandLine);


            }
        }
    }

我相信我有些不对劲但我不确定:

Runtime.getRuntime().exec("E:\\MyLogFile.log");

但是如何解决呢?

最好的问候..

1 个答案:

答案 0 :(得分:3)

要在默认编辑器中打开文件,您无法使用Runtime.exec,您必须使用Desktop.open

if(Desktop.isDesktopSupported()) {
    Desktop.getDesktop().open(new File("E:\\MyLogFile.log"));
}