【问题标题】:by simulating the command shell in java how to execute a file?通过在java中模拟命令shell如何执行文件?
【发布时间】:2014-11-13 04:20:09
【问题描述】:

我制作了一个模拟命令 shell (cmd) 的程序,它的工作方式与我使用线程制作的一样完美,因此用户可以编写新命令而不会阻塞 shell。

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

为此,我使用(文件处理程序)将在每个新会话中创建一个新的 .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");

但是还有什么方法可以解决呢?

最好的问候..

【问题讨论】:

    标签: java shell cmd command


    【解决方案1】:

    要在默认编辑器中打开文件,你不能使用Runtime.exec,你必须使用Desktop.open

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

    【讨论】:

    • 感谢您的快速回答,但我不知道为什么当我在写作 (Showerlog) 时遇到错误!!
    • 错误 2014 年 9 月 18 日 8:25:00 EM witheyul.WithEyul 运行信息:Showerlog 遇到与编写任何其他无效代码时相同的错误,我认为如果(命令.contentEquals("Showerrlog"))
    • @user3526756 请发布完整的堆栈跟踪
    • ***** 欢迎使用 Java 命令外壳 ***** 如果要退出外壳,请键入 END 并按 RETURN。 jsh>Showerrlog 错误 2014 年 9 月 18 日 8:34:58 EM witheyul.WithEyul 运行信息: Showerrlog jsh>
    • 如果我写例如 (hshedw) 或任何其他无效的 shell 命令,我会得到同样的错误.. 我想知道我是否将 ( Showerrlog ) 初始化为 .. if (command.contentEquals("Showerrlog ")) 是对还是错?
    猜你喜欢
    • 2019-11-26
    • 2011-08-20
    • 1970-01-01
    • 1970-01-01
    • 2014-06-12
    • 1970-01-01
    • 2020-05-23
    • 1970-01-01
    • 2018-01-03
    相关资源
    最近更新 更多