简体   繁体   中英

Running Shell commands through java

I am trying to run cmd commands through java. Commands like 'explorer', 'notepad' are running, but commands like 'dir' 'path' are not working it is throwing exception, output says:-

Problem in Executing Command java.io.IOException: Cannot run program "path": CreateProcess error=2, The system cannot find the file specified

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;
        }
    }

see, if any problem in my code.

Program for to list the directories from a specified path
you can go using following code you should get the desire output what you want

/*
 * 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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM