2016-04-13 13 views
1

javaからcmdコマンドを実行しようとしています。 'explorer'、 'notepad'のようなコマンドが実行されていますが、 'dir' 'path'のようなコマンドが例外をスローしていて動作していないと出力に表示されます: -Javaからシェルコマンドを実行する

コマンド実行時の問題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; 
     } 
    } 

参照してください。次のコードを使用して行くことができ、指定されたパス
からディレクトリをリストするThankx

+0

何をしたいcommand' 'の値は何ですか? – BackSlash

+0

私は "dir"というコマンドを与えています – Ankit

+1

問題を示す完全な実例を投稿してください。例外は "dir"ではなく "path"について語ります。 – BackSlash

答えて

0

プログラムあなたが望む出力を取得する必要がありますが

/* 
* 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; 
    } 
} 
関連する問題