簡體   English   中英

通過java運行Shell命令

[英]Running Shell commands through java

我試圖通過java運行cmd命令。 像'explorer','notepad'這樣的命令正在運行,但像'dir''path'這樣的命令無效,它會拋出異常,輸出說: -

執行命令java.io.IOException時出現問題:無法運行程序“path”:CreateProcess error = 2,系統找不到指定的文件

boolean exc(String command){
        Process p;String pingResult="";
        try{
            p=Runtime.getRuntime().exec(command);
            BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                System.out.println(inputLine);
                pingResult += inputLine;
            }
            in.close();

            return true;
        }catch(Exception e){
            System.out.println("Problem in Executing Command "+e.toString());
            return false;
        }
    }

如果我的代碼中有任何問題,請參閱。

用於列出指定路徑中的目錄的程序
你可以使用下面的代碼,你應該得到你想要的欲望輸出

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package checkapplicationisopen;

import java.io.*;
public class TestExec {
    public static void main(String[] args) {
        TestExec testExec=new TestExec();
        System.out.println(testExec.getDirectoryList("C:\\Documents"));
    }

    /**
     * 
     * @param path directory path which you want to retrieve the directory and files
     * @return the list of directories and Files with the size
     * 
     */
    public String getDirectoryList(String path)
    {
        String dirList="";
        try {
            Process p = Runtime.getRuntime().exec("cmd /C dir "+path);
            BufferedReader in = new BufferedReader(
                                new InputStreamReader(p.getInputStream()));
            String line = null;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
                dirList+=line;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return dirList;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM