How to get a list of current open windows / processes with Java?

Does anyone know how to get current open windows or local computer process using Java?

What I'm trying to do is: show the current open task, open windows or a process, as in the Windows Taskmanager, but use a multi-platform approach - using only Java, if possible.

+81
java process
Sep 10 '08 at 16:56
source share
12 answers

This is another approach to analyzing the process list from the ps -e command:

try { String line; Process p = Runtime.getRuntime().exec("ps -e"); BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())); while ((line = input.readLine()) != null) { System.out.println(line); //<-- Parse data here. } input.close(); } catch (Exception err) { err.printStackTrace(); } 

If you use Windows, you should change the line: "Process p = Runtime.getRun ...", etc. (3rd line), for the following:

 Process p = Runtime.getRuntime().exec (System.getenv("windir") +"\\system32\\"+"tasklist.exe"); 

We hope the information helps!

+89
Sep 10 '08 at 18:30
source share

There is an alternative on Windows using JNA :

 import com.sun.jna.Native; import com.sun.jna.platform.win32.*; import com.sun.jna.win32.W32APIOptions; public class ProcessList { public static void main(String[] args) { WinNT winNT = (WinNT) Native.loadLibrary(WinNT.class, W32APIOptions.UNICODE_OPTIONS); WinNT.HANDLE snapshot = winNT.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS, new WinDef.DWORD(0)); Tlhelp32.PROCESSENTRY32.ByReference processEntry = new Tlhelp32.PROCESSENTRY32.ByReference(); while (winNT.Process32Next(snapshot, processEntry)) { System.out.println(processEntry.th32ProcessID + "\t" + Native.toString(processEntry.szExeFile)); } winNT.CloseHandle(snapshot); } } 
+23
Feb 27 '12 at 9:53
source share

Finally, with Java 9+, this is possible with ProcessHandle :

 public static void main(String[] args) { ProcessHandle.allProcesses() .forEach(process -> System.out.println(processDetails(process))); } private static String processDetails(ProcessHandle process) { return String.format("%8d %8s %10s %26s %-40s", process.pid(), text(process.parent().map(ProcessHandle::pid)), text(process.info().user()), text(process.info().startInstant()), text(process.info().commandLine())); } private static String text(Optional<?> optional) { return optional.map(Object::toString).orElse("-"); } 

Exit:

  1 - root 2017-11-19T18:01:13.100Z /sbin/init ... 639 1325 www-data 2018-12-04T06:35:58.680Z /usr/sbin/apache2 -k start ... 23082 11054 huguesm 2018-12-04T10:24:22.100Z /.../java ProcessListDemo 
+16
Jul 12. '17 at 21:46 on
source share

The only way I can do this is to invoke a command line application that does the job for you, and then escape the output (e.g. Linux ps and Window tasklist).

Unfortunately, this will mean that you have to write some parsing procedures to read data from both.

 Process proc = Runtime.getRuntime().exec ("tasklist.exe"); InputStream procOutput = proc.getInputStream (); if (0 == proc.waitFor ()) { // TODO scan the procOutput for your data } 
+9
Sep 10 '08 at 17:00
source share

YAJSW (another Java Wrapper) looks like it has implemented the JNA version of its org.rzo.yajsw.os. The TaskList interface is for win32, linux, bsd and solaris and is licensed under LGPL. I have not tried calling this code directly, but YAJSW works very well when I used it in the past, so you should not have too many worries.

+7
Dec 16 '10 at 21:40
source share

You can easily get a list of running processes using jProcesses

 List<ProcessInfo> processesList = JProcesses.getProcessList(); for (final ProcessInfo processInfo : processesList) { System.out.println("Process PID: " + processInfo.getPid()); System.out.println("Process Name: " + processInfo.getName()); System.out.println("Process Used Time: " + processInfo.getTime()); System.out.println("Full command: " + processInfo.getCommand()); System.out.println("------------------"); } 
+5
Feb 14 '16 at 9:27
source share

There is no such platform neutral method. In version 1.6 for Java, the Desktop class was added, which allows you to transfer methods for viewing, editing, sending, opening and printing URIs. Perhaps this class can be continued to support processes, but I doubt it.

If you're only interested in Java processes, you can use the java.lang.management api to get thread / memory information in the JVM.

+4
Sep 10 '08 at 18:48
source share

For windows, I use the following:

  Process process = new ProcessBuilder("tasklist.exe", "/fo", "csv", "/nh").start(); new Thread(() -> { Scanner sc = new Scanner(process.getInputStream()); if (sc.hasNextLine()) sc.nextLine(); while (sc.hasNextLine()) { String line = sc.nextLine(); String[] parts = line.split(","); String unq = parts[0].substring(1).replaceFirst(".$", ""); String pid = parts[1].substring(1).replaceFirst(".$", ""); System.out.println(unq + " " + pid); } }).start(); process.waitFor(); System.out.println("Done"); 
+4
Jan 13 '17 at 12:44 on
source share

Using ps aux parsing code for linux and tasklist for windows are your best options until something more general appears.

For windows you can link: http://www.rgagnon.com/javadetails/java-0593.html

Linux can stream ps aux results through grep too, which makes processing / searching quick and easy. I am sure you can find something similar for windows too.

+3
May 17 '12 at
source share

This may be useful for applications with a related JRE: I am looking at the name of the folder from which I am running the application: therefore, if you are using the application, follow these steps:

  C:\Dev\build\SomeJavaApp\jre-9.0.1\bin\javaw.exe 

then you can find if it is already running in J9, by:

  public static void main(String[] args) { AtomicBoolean isRunning = new AtomicBoolean(false); ProcessHandle.allProcesses() .filter(ph -> ph.info().command().isPresent() && ph.info().command().get().contains("SomeJavaApp")) .forEach((process) -> { isRunning.set(true); }); if (isRunning.get()) System.out.println("SomeJavaApp is running already"); } 
+1
Jul 17 '18 at 10:32
source share
 package com.vipul; import java.applet.Applet; import java.awt.Checkbox; import java.awt.Choice; import java.awt.Font; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class BatchExecuteService extends Applet { public Choice choice; public void init() { setFont(new Font("Helvetica", Font.BOLD, 36)); choice = new Choice(); } public static void main(String[] args) { BatchExecuteService batchExecuteService = new BatchExecuteService(); batchExecuteService.run(); } List<String> processList = new ArrayList<String>(); public void run() { try { Runtime runtime = Runtime.getRuntime(); Process process = runtime.exec("D:\\server.bat"); process.getOutputStream().close(); InputStream inputStream = process.getInputStream(); InputStreamReader inputstreamreader = new InputStreamReader( inputStream); BufferedReader bufferedrReader = new BufferedReader( inputstreamreader); BufferedReader bufferedrReader1 = new BufferedReader( inputstreamreader); String strLine = ""; String x[]=new String[100]; int i=0; int t=0; while ((strLine = bufferedrReader.readLine()) != null) { // System.out.println(strLine); String[] a=strLine.split(","); x[i++]=a[0]; } // System.out.println("Length : "+i); for(int j=2;j<i;j++) { System.out.println(x[j]); } } catch (IOException ioException) { ioException.printStackTrace(); } } } 
  You can create batch file like 

TASKLIST / v / FI "STATUS eq running" / FO "CSV" / FI "Username eq LHPL002 \ soft" / FI "MEMUSAGE gt 10000" / FI "Windowtitle ne N / A" / NH

0
May 30 '13 at 5:22
source share

Same question ( Windows launches application list using Java )

I found this answer ( https://stackoverflow.com/a/16711111 ) with normal output from Philippe

 try{ Process proc = Runtime.getRuntime().exec("wmic.exe"); BufferedReader input = new BufferedReader(new InputStreamReader(proc.getInputStream())); OutputStreamWriter oStream = new OutputStreamWriter(proc.getOutputStream()); oStream.write("process get caption"); oStream.flush(); oStream.close(); String line; while ((line = input.readLine()) != null){ if(!line.isEmpty() && !line.startsWith("wmic:root\\cli")) { System.out.println(line); } } input.close(); }catch (IOException ioe){ioe.printStackTrace();} 
-one
Nov 05 '17 at 14:29
source share



All Articles