Read from an already open CMD - java

Is there anyway that a Java application can read from an already open CMD window. For example, I opened cmd, ran "dir" and then decided to start my application, is there a way my application can read information that is already in an open CMD window without opening another? thanks in advance

UPDATE: I was hoping that when running one java application, it will check all open CMD windows to make sure that another one of my command line applications was not running before it opened itself.

+3


source to share


1 answer


Just run the output of the executed command to a file.

For example: do dir > spool.txt

and from a java program open the file spool.txt

with FileInputStream

.

To make sure the content is fully written before reading it, you can, for example:

  • use a marker in the recorded file to indicate it
  • check the modification date of the recorded file (if the modification date does not change within a certain period of time, this may be a signal that the recording is complete)

Update with updated question: Check if CMD windows are open

UPDATE: I hope that when one Java application is running, it will check all open CMD windows to make sure another one of my command line applications did not start before opening it by itself.

You can simply list the running Windows processes using the program tasklist.exe

.
The information is retrieved in one line by the process.
Then check if one of the lines starts with cmd.exe

.
If so, then the program is cmd.exe

already running.

Here's some sample code;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class CmdProcessSearch {

    public static void main(String[] args) throws IOException {
        boolean anyCmdProgramOpened = isAnyCmdProgramOpened();
        System.out.println("isOpened = " + anyCmdProgramOpened);
    }
    public static boolean isAnyCmdProgramOpened() {
        Process p;
        try {
            p = Runtime.getRuntime().exec(System.getenv("windir") + "\\system32\\" + "tasklist.exe");
            String line;
            BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
            while ((line = input.readLine()) != null) {
                System.out.println(line);
                if (line.startsWith("cmd.exe")) {
                    return true;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}

      

C:\windows\system32

usually found in your PATH environment variable.
So, it p = Runtime.getRuntime().exec("tasklist.exe");

should be enough, but to prevent any kind of side effect or misconfiguration problem, it's better to specify an absolute path.




New update with new comment: Testing Java application is working

I used this code for another section, but if there is a cmd window running, there is no guarantee that the user has used it to run my program, a batch process;

In this case, if you can install the jdk tools on the client machine, you can check if the Java process is running using your application's main class as the main class.
You can use jps

( Java Virtual Machine Process State Tool ).

Here are the options available:

OPTIONS

The jps command supports a number of options that modify the output of the command. These parameters can be changed or deleted. in future.

-q

Suppress the output of the class name, JAR file name, and arguments passed to the main method, creating only a list of local virtual machine identifiers.

-m

Print the arguments passed to the main method. The output can be null for embedded JVMs.

-l

Output the fully qualified package name for the main application class or the fully qualified pathname to the application JAR file.

-v

Print arguments passed to JVM.

-V

Display the arguments passed to the JVM via a flags file (the .hotspotrc file or the file specified in -XX: Flags = argument).

-Joption

Pass option to java launcher called by jps. For example, -J-Xms48m sets the boot memory to 48 megabytes. It is a common convention that -J passes parameters to the underlying virtual machine execution of Java applications.

jps -l

which outputs the fully qualified package name for the main application class or the fully qualified pathname to the application's JAR file.

Here's some sample code by searching for the main class of the application process.JavaProcessSearch

:

package process;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class JavaProcessSearch {

    public static void main(String[] args) throws IOException {
        boolean isProcessRunning = isAJavaProcessWithMainClass("process.JavaProcessSearch");
        System.out.println(isProcessRunning);
    }

    public static boolean isAJavaProcessWithMainClass(String mainClass) {
        Process p;
        try {
             String javaHome = System.getenv("JAVA_HOME");
             p = Runtime.getRuntime().exec(javaHome + File.separator + "bin/jps -l");

            String line;
            BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
            while ((line = input.readLine()) != null) {
                System.out.println(line);
                if (line.contains(mainClass)) {
                    return true;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return false;
    }

}

      

If you cannot install the jdk tools, you can save "somewhere" on the client machine, the process id of the application when it is started. You can get this information in the following manner: ManagementFactory.getRuntimeMXBean().getName()

.
When it is no longer running (stopped or crashed), you can remove this process id information.
When the ia app starts, if the process id is retrieved on the client machine, you don't allow the app to run.
For a stopped application, the shutdown tap must do the job.
In the event of an application crash, you can use a deamon thread that checks on a regular basis if the application is always running based on the stored process id.

+1


source







All Articles