- Starting a process in Java?
- 3 Answers 3
- How do I run a Java program from the command line on Windows?
- 12 Answers 12
- How to find the process id of a running Java process on Windows? And how to kill the process alone?
- 8 Answers 8
- How can we stop a running java process through Windows cmd?
- 11 Answers 11
- Start
- How to get a list of current open windows/process with Java?
- 14 Answers 14
Starting a process in Java?
Is there a way to start a process in Java? in .Net this is done with for example:
Is there an equivalent in Java so I can then let the user find the application and then it would work for any OS?
3 Answers 3
You can get the local path using System properties or a similar approach.
See Runtime.exec() and the Process class. In its simplest form:
Note that you also need to read the process’ output (eg: myProcess.getInputStream() ) — or the process will hang on some systems. This can be highly confusing the first time, and should be included in any introduction to these APIs. See James P.’s response for an example.
You might also want to look into the new ProcessBuilder class, which makes it easier to change environment variables and to invoke subprocesses :
The Java Class Library represents external processes using the java.lang.Process class. Processes can be spawned using a java.lang.ProcessBuilder :
or the older interface exposed by the overloaded exec methods on the java.lang.Runtime class:
Both of these will code snippets will spawn a new process, which usually executes asynchronously and can be interacted with through the resulting Process object. If you need to check that the process has finished (or wait for it to finish), don’t forget to check that the exit value (exit code) returned by process.exitValue() or process.waitFor() is as expected (0 for most programs), since no exception is thrown if the process exits abnormally.
Also note that additional code is often necessary to handle the process’s I/O correctly, as described in the documentation for the Process class (emphasis added):
By default, the created subprocess does not have its own terminal or console. All its standard I/O (i.e. stdin, stdout, stderr) operations will be redirected to the parent process, where they can be accessed via the streams obtained using the methods getOutputStream(), getInputStream(), and getErrorStream(). The parent process uses these streams to feed input to and get output from the subprocess. Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, or even deadlock.
One way to make sure that I/O is correctly handled and that the exit value indicates success is to use a library like jproc that deals with the intricacies of capturing stdout and stderr, and offers a simple synchronous interface to run external processes:
How do I run a Java program from the command line on Windows?
I’m trying to execute a Java program from the command line in Windows. Here is my code:
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)?
12 Answers 12
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.
This tells the system where to find JDK programs.
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.
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!
To complete the answer :
Compile the Java File to a *.class file
- This will create a TheJavaFile.class file
Execution of the Java File
Creation of an executable *.jar file
You’ve got two options here —
With an external manifest file :
Create the manifest file say — MANIFEST.mf
The MANIFEST file is nothing but an explicit entry of the Main Class
jar -cvfm TheJavaFile.jar MANIFEST.mf TheJavaFile.class
Executable by Entry Point:
To run the Jar File
In case your Java class is in some package. Suppose your Java class named ABC.java is present in com.hello.programs , then you need to run it with the package name.
Compile it in the usual way:
But to run it, you need to give the package name and then your java class name:
Complile a Java file to generate a class:
Execute the generated class:
Assuming the file is called «CopyFile.java», do the following:
The first line compiles the source code into executable byte code. The second line executes it, first adding the current directory to the class path (just in case).
Since Java 11, java command line tool has been able to run a single-file source-code directly. e.g.
This was an enhancement with JEP 330: https://openjdk.java.net/jeps/330
For the details of the usage and the limitations, see the manual of your Java implementation such as one provided by Oracle: https://docs.oracle.com/en/java/javase/11/tools/java.html
It is easy. If you have saved your file as A.text first thing you should do is save it as A.java. Now it is a Java file.
Now you need to open cmd and set path to you A.java file before compile it. you can refer this for that.
Then you can compile your file using command
Then run it using
So that is how you compile and run a java program in cmd. You can also go through these material that is Java in depth lessons. Lot of things you need to understand in Java is covered there for beginners.
You can compile any java source using javac in command line ; eg, javac CopyFile.java. To run : java CopyFile. You can also compile all java files using javac *.java as long as they’re in the same directory
If you’re having an issue resulting with «could not find or load main class» you may not have jre in your path. Have a look at this question: Could not find or load main class
On Windows 7 I had to do the following:
quick way
- Install JDK http://www.oracle.com/technetwork/java/javase/downloads
- in windows, browse into «C:\Program Files\Java\jdk1.8.0_91\bin» (or wherever the latest version of JDK is installed), hold down shift and right click on a blank area within the window and do «open command window here» and this will give you a command line and access to all the BIN tools. «javac» is not by default in the windows system PATH environment variable.
- Follow comments above about how to compile the file («javac MyFile.java» then «java MyFile») https://stackoverflow.com/a/33149828/194872
long way
- Install JDK http://www.oracle.com/technetwork/java/javase/downloads/index.html
- After installing, in edits the Windows PATH environment variable and adds the following to the path C:\ProgramData\Oracle\Java\javapath. Within this folder are symbolic links to a handful of java executables but «javac» is NOT one of them so when trying to run «javac» from Windows command line it throws an error.
- I edited the path: Control Panel -> System -> Advanced tab -> «Environment Variables. » button -> scroll down to «Path», highlight and edit -> replaced the «C:\ProgramData\Oracle\Java\javapath» with a direct path to the java BIN folder «C:\Program Files\Java\jdk1.8.0_91\bin».
This likely breaks when you upgrade your JDK installation but you have access to all the command line tools now.
How to find the process id of a running Java process on Windows? And how to kill the process alone?
I want to kill the particular Java process in Windows, like in Linux ( ps -aux to get processid and then kill processid to kill the process).
8 Answers 8
You can use the jps utility that is included in the JDK to find the process id of a Java process. The output will show you the name of the executable JAR file or the name of the main class.
Then use the Windows task manager to terminate the process. If you want to do it on the command line, use
You can also find the PID of a java program with the task manager. You enable the PID and Command Line columns View -> Select Columns and are then able to find the right process.
Your result will be something like this :
After setting the path of your jdk use JPS .Then You can eaisly kill it by Task Manager
JPS will give you all java processes
This will work even when there are multiple instance of jar is running
The solution I found is very simple. Use Window’s WMIC & Java’s Runtime to locate & kill the process.
Part 1: You need to put some sort of identifier into your app’s startup command line. E.g. something like:
Part 2: When you run your app, make sure to include the string. Let’s say you start it from within Java, do the following:
Part 3: To kill the process, use Window’s WMIC. Just make sure you app was started containing your id from above:
In windows XP and later, there’s a command: tasklist that lists all process id’s.
For killing a process in Windows, see:
You can execute OS-commands in Java by:
If you need to handle the output of a command, see example: using Runtime.exec() in Java
This is specific to Windows. I was facing the same issue where I have to kill one specific java program using taskkill. When I run the java program, tasklist was showing the same program with Image name set as java.exe. But killing it using taskkill /F java.exe will stop all other java applications other than intended one which is not required.
So I run the same java program using:
Here start command will open a new window and run the java program with window’s title set to MyProgramName.
Now to kill this java-program use the following taskkill command:
Your Java program will be killed only. Rest will be unaffected.
How can we stop a running java process through Windows cmd?
I am a newbie in cmd, so please allow me to ask a stupid question: How can we stop a running Java process through Windows cmd?
For example, if we start Jetty (a mini web server) with the following command:
How do we find the process and stop it later?
Obviously the following command does not work:
11 Answers 11
It is rather messy but you need to do something like the following:
(This kind of thing is much easier if you have a UNIX / LINUX system . or if you run Cygwin or similar on Windows.)
When I ran taskkill to stop the javaw.exe process it would say it had terminated but remained running. The jqs process (java qucikstart) needs to be stopped also. Running this batch file took care of the issue.
I like this one.
You can actually kill a process on a remote machine the same way.
wmic is awesome!
Normally I don’t have that many Java processes open so
should suffice. This will kill all instances of Java, though.
Open the windows cmd. First list all the java processes,
now get the name and run below command,
or simply kill the process ID
sample 🙂
In case you want to kill not all java processes but specif jars running. It will work for multiple jars as well.
Else taskkill /im java.exe will work to kill all java processes
The answer which suggests something like taskkill /f /im java.exe will probably work, but if you want to kill only one java process instead of all, I can suggest doing it with the help of window titles. Expample:
Start
start «MyProgram» «C:/Program Files/Java/jre1.8.0_201/bin/java.exe» -jar MyProgram.jar
taskkill /F /FI «WINDOWTITLE eq MyProgram» /T
How to get a list of current open windows/process with Java?
Does any one know how do I get the current open windows or process of a local machine using Java?
What I’m trying to do is: list the current open task, windows or process open, like in Windows Taskmanager, but using a multi-platform approach — using only Java if it’s possible.
14 Answers 14
This is another approach to parse the the process list from the command «ps -e«:
If you are using Windows, then you should change the line: «Process p = Runtime.getRun. » etc. (3rd line), for one that looks like this:
Hope the info helps!
Finally, with Java 9+ it is possible with ProcessHandle :
On Windows there is an alternative using JNA:
The only way I can think of doing it is by invoking a command line application that does the job for you and then screenscraping the output (like Linux’s ps and Window’s tasklist).
Unfortunately, that’ll mean you’ll have to write some parsing routines to read the data from both.
YAJSW (Yet Another Java Service Wrapper) looks like it has JNA-based implementations of its org.rzo.yajsw.os.TaskList interface for win32, linux, bsd and solaris and is under an LGPL license. I haven’t tried calling this code directly, but YAJSW works really well when I’ve used it in the past, so you shouldn’t have too many worries.
You can easily retrieve the list of running processes using jProcesses
There is no platform-neutral way of doing this. In the 1.6 release of Java, a «Desktop» class was added the allows portable ways of browsing, editing, mailing, opening, and printing URI’s. It is possible this class may someday be extended to support processes, but I doubt it.
If you are only curious in Java processes, you can use the java.lang.management api for getting thread/memory information on the JVM.
For windows I use following:
This might be useful for apps with a bundled JRE: I scan for the folder name that i’m running the application from: so if you’re application is executing from:
then you can find if it’s already running in J9, by:
Using code to parse ps aux for linux and tasklist for windows are your best options, until something more general comes along.
Linux can pipe the results of ps aux through grep too, which would make processing/searching quick and easy. I’m sure you can find something similar for windows too.
The below program will be compatible with Java 9+ version only.
To get the CurrentProcess information,
For all running processes,
We have to use process.getOutputStream.close() otherwise it will get locked in while loop.
TASKLIST /v /FI «STATUS eq running» /FO «CSV» /FI «Username eq LHPL002\soft» /FI «MEMUSAGE gt 10000» /FI «Windowtitle ne N/A» /NH