Java execute program windows

How do I execute Windows commands in Java?

I’m working on a project, and it will give you a list of Windows commands. When you select one, it will perform that command. However, I don’t know how to do that. I was going to do it in Visual C#, or C++, but C++ classes are too complicated, and I don’t want to make the forms and junk in Visual C# (really bad at console applications).

Search for «java run command» to help refine the question better — e.g. which part(s) are there issues with? Note that some commands do not make sense outside of a shell. These include cd and the like and should be emulated accordingly. (Although, I would likely consider it a «better» investment of time to emulate all supported commands — i.e. move/copy/list/delete? — in Java itself or open up a real shell and let the user do whatever they want.)

Also, if you’re on Windows, just use VS Express (free) + C# (which is really about the same «difficulty» as Java). It Just Works (TM), including WinForms.

5 Answers 5

Runtime.getRuntime().exec("ENTER COMMAND HERE"); 

an example. 1. create cmd 2. write to cmd -> call a command.

Take advantage of the ProcessBuilder .

It makes it easier to build the process parameters and takes care of issues with having spaces in commands automatically.

public class TestProcessBuilder < public static void main(String[] args) < try < ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "dir"); pb.redirectError(); Process p = pb.start(); InputStreamConsumer isc = new InputStreamConsumer(p.getInputStream()); isc.start(); int exitCode = p.waitFor(); isc.join(); System.out.println("Process terminated with " + exitCode); >catch (IOException | InterruptedException exp) < exp.printStackTrace(); >> public static class InputStreamConsumer extends Thread < private InputStream is; public InputStreamConsumer(InputStream is) < this.is = is; >@Override public void run() < try < int value = -1; while ((value = is.read()) != -1) < System.out.print((char)value); >> catch (IOException exp) < exp.printStackTrace(); >> > > 

I’d generally build a all purpose class, which you could pass in the «command» (such as «dir») and it’s parameters, that would append the call out to the OS automatically. I would also included the ability to get the output, probably via a listener callback interface and even input, if the command allowed input.

Читайте также:  Javascript random from array

Источник

How to Run External Program in Java

From your Java program, it is possible to run other applications in your operating system. This enables you to make use of system programs and command line utilities from your Java program. Here are some typical uses of this feature when running your Java program in Windows,

  • You want to invoke a Windows program such as Notepad
  • You want to invoke a command line utility such as Check disk (chkdsk) or IP information (ipconfig)
  • You want to access the Windows command interpreter and access some of its features such as «dir» command or «find» command. In this case, please note that the program you want to access is cmd.exe and commands like «dir» and «find» are arguments to cmd.exe. Also when directly invoked, cmd.exe doesn’t terminate. If you want cmd.exe to terminate immediately, you should pass the /C argument.

We have provided sample programs for each of the use cases above. The overall approach here is same (we will use Runtime.exec method), but there are some subtle differences you need to be aware of.

The following program demonstrates how you can execute a Windows program such as Notepad from your Java program,

/** * Runs external application from this Java program */ public class RunProgram < public static void main(String[] args) < RunProgram rp = new RunProgram(); rp.openNotePad(); >/** * Runs Notepad program in the Windows system. Please note that this assumes * you are running this program on Windows. */ private void openNotePad() < Runtime rt = Runtime.getRuntime(); try < Process p = rt.exec("notepad"); >catch(Exception ex) < ex.printStackTrace(); >> >

This following example demonstrates how you can execute a command line program in Windows from your Java program. This program will also print the results of the command. Note that in this case we are using another version of the Runtime.exec method. This program runs «ipconfig» command with /all command line argument. This would print the complete IP address configuration of the system.

import java.io.BufferedReader; import java.io.InputStreamReader; /** * Runs another application from a Java program */ public class RunProgram2 < public static void main(String[] args) < RunProgram2 rp = new RunProgram2(); rp.printIPInfo(); >/** * Print complete IP address info using the command ipconfig /all */ private void printIPInfo() < Runtime rt = Runtime.getRuntime(); String[] commandAndArguments = ; try < Process p = rt.exec(commandAndArguments); String response = readProcessOutput(p); System.out.println(response); >catch(Exception ex) < ex.printStackTrace(); >> /** * Reads the response from the command. Please note that this works only * if the process returns immediately. * @param p * @return * @throws Exception */ private String readProcessOutput(Process p) throws Exception < BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String response = ""; String line; while ((line = reader.readLine()) != null) < response += line+"\r\n"; >reader.close(); return response; > >

In the final example, we invoke the command line program (cmd.exe) of the Windows system and then execute commands supported by it. By default cmd.exe is blocking and to terminate it immediately you need to pass the command line option /C. The following program prints the directory listing of C drive (C:\) using the «dir» command of «cmd.exe».

import java.io.BufferedReader; import java.io.InputStreamReader; public class RunProgram3 < public static void main(String[] args) < RunProgram3 rp = new RunProgram3(); rp.getDirectoryListing(); >/** * Runs cmd.exe from Java program and then invokes dir command to list C:\ drive. * The /C option is necessary for the program */ private void getDirectoryListing() < Runtime rt = Runtime.getRuntime(); String[] commandAndArguments = ; try < Process p = rt.exec(commandAndArguments); String listing = readProcessOutput(p); System.out.println(listing); //p.waitFor(); >catch(Exception ex) < ex.printStackTrace(); >> /** * Reads the response from the command. Please note that this works only * if the process returns immediately. * @param p * @return * @throws Exception */ private String readProcessOutput(Process p) throws Exception < BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String response = ""; String line; while ((line = reader.readLine()) != null) < response += line+"\r\n"; >reader.close(); return response; > >

If you are not reading the response from the external program and if you want to wait for the external program to finish before you continue processing, you can use the Process.waitFor() method. This will block your program till the external program completes execution.

Источник

How do I run a Java program from the command line on Windows?

I’m not sure how to execute the program — any help?
Is this possible on Windows?
Why is it different than another environment (I thought JVM was write once, run anywhere)?

I’m at the command line now, do I need to save my txt files in the same folder as the program for them to be invoked?

@Elizabeth Turner first you have to make sure that you have installed JRE (Java Runtime Env) and that it’s accessible form every folder (the path to Java/Javac is included in the PATH env variable). Then run the commands I wrote above from the same folder in which CopyFile.java is located.

13 Answers 13

Let’s say your file is in C:\mywork\

Run Command Prompt

This makes C:\mywork the current directory.

This displays the directory contents. You should see filenamehere.java among the files.

C:\mywork> set path=%path%;C:\Program Files\Java\jdk1.5.0_09\bin 

This tells the system where to find JDK programs.

C:\mywork> javac filenamehere.java 

This runs javac.exe, the compiler. You should see nothing but the next system prompt.

javac has created the filenamehere.class file. You should see filenamehere.java and filenamehere.class among the files.

C:\mywork> java filenamehere 

This runs the Java interpreter. You should then see your program output.

If the system cannot find javac, check the set path command. If javac runs but you get errors, check your Java text. If the program compiles but you get an exception, check the spelling and capitalization in the file name and the class name and the java HelloWorld command. Java is case-sensitive!

Источник

How to run exe file in Java program

This code runs the file. This file have some section that I can click it and run different part of it. Is it possible that I can use a code to access to that sections and run them in Java instead of clicking it? edited code :

 Process process = Runtime.getRuntime().exec( "cmd.exe /C start C:/Users/123/Desktop/nlp.exe" ); Robot bot = new Robot(); bot.mouseMove(100, 100); bot.mousePress(InputEvent.BUTTON1_MASK); bot.mouseRelease(InputEvent.BUTTON1_MASK); 

I don’t quite get your question but if nlp.exe is the application where you have to do a click selection then please check whether the application supports command line parameters.

3 Answers 3

You can send a click signal to the system and specify its position on the screen. Check this question

You have to compute it on your own. I don’t think you can get any information about the content of the GUI.

it takes time to program run, so first robot click and then program run. what should I do to first run program and after that robot click?

Use java.awt.Robot to generate a system mouse click for an external program.

There is no built-in way with Java to get an external window’s coordinates, but it can be done using JNA. See this answer:

Your comments and editing are changing the question, which is making answering here almost pointless. Per your last edit to the question though, if I understand correctly, you are now asking if possible to somehow trigger an event in the external application with Java, without triggering the mouse click. In this case I think the answer is highly specific to the individual program.

If the event can be triggered via keypresses, then that might an another non-mouse option using java.awt.Robot .

If the program generates/responds to a Windows Message (at the windows api level), you could possibly send the same message via JNA and the windows api SendMessage . However, that can get complicated and requires that you are familiar with windows API and techniques for finding and working with those messages.

Источник

Оцените статью