<p>Does any one know how do I get the current open windows or process of a local machine using Java?  </p>

<p>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.</p>

[{'answer_id': 54696, 'author': 'jodonnell', 'author_id': 4223, 'author_profile': 'https://Stackoverflow.com/users/4223', 'pm_score': 3, 'selected': False, 'text': '<p>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). </p>\n\n<p>Unfortunately, that\'ll mean you\'ll have to write some parsing routines to read the data from both.</p>\n\n<pre><code>Process proc = Runtime.getRuntime().exec ("tasklist.exe");\nInputStream procOutput = proc.getInputStream ();\nif (0 == proc.waitFor ()) {\n    // TODO scan the procOutput for your data\n}\n</code></pre>\n'}, {'answer_id': 54950, 'author': 'ràmäyác', 'author_id': 4358, 'author_profile': 'https://Stackoverflow.com/users/4358', 'pm_score': 7, 'selected': False, 'text': '<p>This is another approach to parse the the process list from the command "<strong>ps -e</strong>":</p>\n\n<pre><code>try {\n    String line;\n    Process p = Runtime.getRuntime().exec("ps -e");\n    BufferedReader input =\n            new BufferedReader(new InputStreamReader(p.getInputStream()));\n    while ((line = input.readLine()) != null) {\n        System.out.println(line); //&lt;-- Parse data here.\n    }\n    input.close();\n} catch (Exception err) {\n    err.printStackTrace();\n}\n</code></pre>\n\n<p>If you are using Windows, then you should change the line: "Process p = Runtime.getRun..." etc... (3rd line), for one that looks like this:</p>\n\n<pre><code>Process p = Runtime.getRuntime().exec\n    (System.getenv("windir") +"\\\\system32\\\\"+"tasklist.exe");\n</code></pre>\n\n<p>Hope the info helps!</p>\n'}, {'answer_id': 55002, 'author': 'hazzen', 'author_id': 5066, 'author_profile': 'https://Stackoverflow.com/users/5066', 'pm_score': 2, 'selected': False, 'text': '<p>There is no platform-neutral way of doing this. In the 1.6 release of Java, a "<a href="http://java.sun.com/javase/6/docs/api/java/awt/Desktop.html" rel="nofollow noreferrer">Desktop</a>" 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.</p>\n\n<p>If you are only curious in Java processes, you can use the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/management/ManagementFactory.html" rel="nofollow noreferrer">java.lang.management</a> api for getting thread/memory information on the JVM.</p>\n'}, {'answer_id': 4465630, 'author': 'SamWest', 'author_id': 545373, 'author_profile': 'https://Stackoverflow.com/users/545373', 'pm_score': 3, 'selected': False, 'text': '<p><a href="http://yajsw.sourceforge.net/" rel="noreferrer">YAJSW</a> (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.</p>\n'}, {'answer_id': 9463010, 'author': 'Emmanuel Bourg', 'author_id': 525725, 'author_profile': 'https://Stackoverflow.com/users/525725', 'pm_score': 5, 'selected': False, 'text': '<p>On Windows there is an alternative using <a href="https://github.com/twall/jna" rel="noreferrer">JNA</a>:</p>\n\n<pre><code>import com.sun.jna.Native;\nimport com.sun.jna.platform.win32.*;\nimport com.sun.jna.win32.W32APIOptions;\n\npublic class ProcessList {\n\n    public static void main(String[] args) {\n        WinNT winNT = (WinNT) Native.loadLibrary(WinNT.class, W32APIOptions.UNICODE_OPTIONS);\n\n        WinNT.HANDLE snapshot = winNT.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS, new WinDef.DWORD(0));\n\n        Tlhelp32.PROCESSENTRY32.ByReference processEntry = new Tlhelp32.PROCESSENTRY32.ByReference();\n\n        while (winNT.Process32Next(snapshot, processEntry)) {\n            System.out.println(processEntry.th32ProcessID + "\\t" + Native.toString(processEntry.szExeFile));\n        }\n\n        winNT.CloseHandle(snapshot);\n    }\n}\n</code></pre>\n'}, {'answer_id': 10638518, 'author': 'James Oravec', 'author_id': 1190934, 'author_profile': 'https://Stackoverflow.com/users/1190934', 'pm_score': 2, 'selected': False, 'text': '<p>Using code to parse <code>ps aux</code> for linux and <code>tasklist</code> for windows are your best options, until something more general comes along.</p>\n\n<p>For windows, you can reference: <a href="http://www.rgagnon.com/javadetails/java-0593.html" rel="nofollow">http://www.rgagnon.com/javadetails/java-0593.html</a></p>\n\n<p>Linux can pipe the results of <code>ps aux</code> through <code>grep</code> too, which would make processing/searching quick and easy. I\'m sure you can find something similar for windows too.</p>\n'}, {'answer_id': 16828521, 'author': 'Panchotiya Vipul', 'author_id': 2114999, 'author_profile': 'https://Stackoverflow.com/users/2114999', 'pm_score': 0, 'selected': False, 'text': '<pre><code>package com.vipul;\n\nimport java.applet.Applet;\nimport java.awt.Checkbox;\nimport java.awt.Choice;\nimport java.awt.Font;\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class BatchExecuteService extends Applet {\n    public Choice choice;\n\n    public void init() \n    {\n        setFont(new Font("Helvetica", Font.BOLD, 36));\n        choice = new Choice();\n    }\n\n    public static void main(String[] args) {\n        BatchExecuteService batchExecuteService = new BatchExecuteService();\n        batchExecuteService.run();\n    }\n\n    List&lt;String&gt; processList = new ArrayList&lt;String&gt;();\n\n    public void run() {\n        try {\n            Runtime runtime = Runtime.getRuntime();\n            Process process = runtime.exec("D:\\\\server.bat");\n            process.getOutputStream().close();\n            InputStream inputStream = process.getInputStream();\n            InputStreamReader inputstreamreader = new InputStreamReader(\n                    inputStream);\n            BufferedReader bufferedrReader = new BufferedReader(\n                    inputstreamreader);\n            BufferedReader bufferedrReader1 = new BufferedReader(\n                    inputstreamreader);\n\n            String strLine = "";\n            String x[]=new String[100];\n            int i=0;\n            int t=0;\n            while ((strLine = bufferedrReader.readLine()) != null) \n            {\n        //      System.out.println(strLine);\n                String[] a=strLine.split(",");\n                x[i++]=a[0];\n            }\n    //      System.out.println("Length : "+i);\n\n            for(int j=2;j&lt;i;j++)\n            {\n                System.out.println(x[j]);\n            }\n        }\n        catch (IOException ioException) \n        {\n            ioException.printStackTrace();\n        }\n\n    }\n}\n</code></pre>\n\n<blockquote>\n<pre><code>   You can create batch file like \n</code></pre>\n  \n  <p>TASKLIST /v /FI "STATUS eq running" /FO "CSV" /FI "Username eq LHPL002\\soft"  /FI "MEMUSAGE gt 10000"  /FI "Windowtitle ne N/A" /NH</p>\n</blockquote>\n'}, {'answer_id': 35390242, 'author': 'profesor_falken', 'author_id': 1774614, 'author_profile': 'https://Stackoverflow.com/users/1774614', 'pm_score': 3, 'selected': False, 'text': '<p>You can easily retrieve the list of running processes using <a href="https://github.com/profesorfalken/jProcesses" rel="nofollow noreferrer">jProcesses</a></p>\n\n<pre><code>List&lt;ProcessInfo&gt; processesList = JProcesses.getProcessList();\n\nfor (final ProcessInfo processInfo : processesList) {\n    System.out.println("Process PID: " + processInfo.getPid());\n    System.out.println("Process Name: " + processInfo.getName());\n    System.out.println("Process Used Time: " + processInfo.getTime());\n    System.out.println("Full command: " + processInfo.getCommand());\n    System.out.println("------------------");\n}\n</code></pre>\n'}, {'answer_id': 41634959, 'author': 'Stepan Yakovenko', 'author_id': 517073, 'author_profile': 'https://Stackoverflow.com/users/517073', 'pm_score': 2, 'selected': False, 'text': '<p>For windows I use following:</p>\n\n<pre class="lang-java prettyprint-override"><code>Process process = new ProcessBuilder("tasklist.exe", "/fo", "csv", "/nh").start();\nnew Thread(() -&gt; {\n    Scanner sc = new Scanner(process.getInputStream());\n    if (sc.hasNextLine()) sc.nextLine();\n    while (sc.hasNextLine()) {\n        String line = sc.nextLine();\n        String[] parts = line.split(",");\n        String unq = parts[0].substring(1).replaceFirst(".$", "");\n        String pid = parts[1].substring(1).replaceFirst(".$", "");\n        System.out.println(unq + " " + pid);\n    }\n}).start();\nprocess.waitFor();\nSystem.out.println("Done");\n</code></pre>\n'}, {'answer_id': 45068036, 'author': 'Hugues M.', 'author_id': 6730571, 'author_profile': 'https://Stackoverflow.com/users/6730571', 'pm_score': 7, 'selected': True, 'text': '<p>Finally, with Java 9+ it is possible with <a href="https://docs.oracle.com/javase/9/docs/api/java/lang/ProcessHandle.html" rel="noreferrer"><code>ProcessHandle</code></a>:</p>\n\n<pre><code>public static void main(String[] args) {\n    ProcessHandle.allProcesses()\n            .forEach(process -&gt; System.out.println(processDetails(process)));\n}\n\nprivate static String processDetails(ProcessHandle process) {\n    return String.format("%8d %8s %10s %26s %-40s",\n            process.pid(),\n            text(process.parent().map(ProcessHandle::pid)),\n            text(process.info().user()),\n            text(process.info().startInstant()),\n            text(process.info().commandLine()));\n}\n\nprivate static String text(Optional&lt;?&gt; optional) {\n    return optional.map(Object::toString).orElse("-");\n}\n</code></pre>\n\n<p>Output:\n</p>\n\n<pre><code>    1        -       root   2017-11-19T18:01:13.100Z /sbin/init\n  ...\n  639     1325   www-data   2018-12-04T06:35:58.680Z /usr/sbin/apache2 -k start\n  ...\n23082    11054    huguesm   2018-12-04T10:24:22.100Z /.../java ProcessListDemo\n</code></pre>\n'}, {'answer_id': 51379205, 'author': 'wax_lyrical', 'author_id': 3987353, 'author_profile': 'https://Stackoverflow.com/users/3987353', 'pm_score': 2, 'selected': False, 'text': '<p>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:</p>\n\n<pre><code>C:\\Dev\\build\\SomeJavaApp\\jre-9.0.1\\bin\\javaw.exe\n</code></pre>\n\n<p>then you can find if it\'s already running in J9, by:</p>\n\n<pre class="lang-java prettyprint-override"><code>public static void main(String[] args) {\n    AtomicBoolean isRunning = new AtomicBoolean(false);\n    ProcessHandle.allProcesses()\n            .filter(ph -&gt; ph.info().command().isPresent() &amp;&amp; ph.info().command().get().contains("SomeJavaApp"))\n            .forEach((process) -&gt; {\n                isRunning.set(true);\n            });\n    if (isRunning.get()) System.out.println("SomeJavaApp is running already");\n}\n</code></pre>\n'}, {'answer_id': 53966059, 'author': 'Dylan Wedman', 'author_id': 10844972, 'author_profile': 'https://Stackoverflow.com/users/10844972', 'pm_score': 0, 'selected': False, 'text': '<p>This is my code for a function that gets the tasks and gets their names, also adding them into a list to be accessed from a list. It creates temp files with the data, reads the files and gets the task name with the .exe suffix, and arranges the files to be deleted when the program has exited with System.exit(0), it also hides the processes being used to get the tasks and also java.exe so that the user can\'t accidentally kill the process that runs the program all together.</p>\n\n<pre><code>private static final DefaultListModel tasks = new DefaultListModel();\n\npublic static void getTasks()\n{\n    new Thread()\n    {\n        @Override\n        public void run()\n        {\n            try \n            {\n                File batchFile = File.createTempFile("batchFile", ".bat");\n                File logFile = File.createTempFile("log", ".txt");\n                String logFilePath = logFile.getAbsolutePath();\n                try (PrintWriter fileCreator = new PrintWriter(batchFile)) \n                {\n                    String[] linesToPrint = {"@echo off", "tasklist.exe &gt;&gt;" + logFilePath, "exit"};\n                    for(String string:linesToPrint)\n                    {\n                        fileCreator.println(string);\n                    }\n                    fileCreator.close();\n                }\n                int task = Runtime.getRuntime().exec(batchFile.getAbsolutePath()).waitFor();\n                if(task == 0)\n                {\n                    FileReader fileOpener = new FileReader(logFile);\n                    try (BufferedReader reader = new BufferedReader(fileOpener))\n                    {\n                        String line;\n                        while(true)\n                        {\n                            line = reader.readLine();\n                            if(line != null)\n                            {\n                                if(line.endsWith("K"))\n                                {\n                                    if(line.contains(".exe"))\n                                    {\n                                        int index = line.lastIndexOf(".exe", line.length());\n                                        String taskName = line.substring(0, index + 4);\n                                        if(! taskName.equals("tasklist.exe") &amp;&amp; ! taskName.equals("cmd.exe") &amp;&amp; ! taskName.equals("java.exe"))\n                                        {\n                                            tasks.addElement(taskName);\n                                        }\n                                    }\n                                }\n                            }\n                            else\n                            {\n                                reader.close();\n                                break;\n                            }\n                        }\n                    }\n                }\n                batchFile.deleteOnExit();\n                logFile.deleteOnExit();\n            } \n            catch (FileNotFoundException ex) \n            {\n                Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);\n            } \n            catch (IOException | InterruptedException ex) \n            {\n                Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);\n            }\n            catch (NullPointerException ex)\n            {\n                // This stops errors from being thrown on an empty line\n            }\n        }\n    }.start();\n}\n\npublic static void killTask(String taskName)\n{\n    new Thread()\n    {\n        @Override\n        public void run()\n        {\n            try \n            {\n                Runtime.getRuntime().exec("taskkill.exe /IM " + taskName);\n            } \n            catch (IOException ex) \n            {\n                Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);\n            }\n        }\n    }.start();\n}\n</code></pre>\n'}, {'answer_id': 58663666, 'author': 'Nallamachu', 'author_id': 2159525, 'author_profile': 'https://Stackoverflow.com/users/2159525', 'pm_score': 2, 'selected': False, 'text': '<p>The below program will be compatible with <strong>Java 9+</strong> version only...</p>\n\n<p>To get the CurrentProcess information,</p>\n\n<pre><code>public class CurrentProcess {\n    public static void main(String[] args) {\n        ProcessHandle handle = ProcessHandle.current();\n        System.out.println("Current Running Process Id: "+handle.pid());\n        ProcessHandle.Info info = handle.info();\n        System.out.println("ProcessHandle.Info : "+info);\n    }\n}\n</code></pre>\n\n<p>For all running processes,</p>\n\n<pre><code>import java.util.List;\nimport java.util.stream.Collectors;\n\npublic class AllProcesses {\n    public static void main(String[] args) {\n        ProcessHandle.allProcesses().forEach(processHandle -&gt; {\n            System.out.println(processHandle.pid()+" "+processHandle.info());\n        });\n    }\n}\n</code></pre>\n'}, {'answer_id': 60378892, 'author': 'Jijo Joy', 'author_id': 12954467, 'author_profile': 'https://Stackoverflow.com/users/12954467', 'pm_score': 2, 'selected': False, 'text': '<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">\r\n<div class="snippet-code">\r\n<pre class="snippet-code-js lang-js prettyprint-override"><code>    String line;\r\n    Process process = Runtime.getRuntime().exec("ps -e");\r\n    process.getOutputStream().close();\r\n    BufferedReader input =\r\n            new BufferedReader(new InputStreamReader(process.getInputStream()));\r\n    while ((line = input.readLine()) != null) {\r\n        System.out.println(line); //&lt;-- Parse data here.\r\n    }\r\n    input.close();</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>We have to use <code>process.getOutputStream.close()</code> otherwise it will get locked in while loop.</p>\n'}]
['https://Stackoverflow.com/questions/54686', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4358/']