Use Java code to close the specified port under Program-windows

Source: Internet
Author: User
Tags string find stringbuffer

Please indicate the author and source at the top of the Page.

one: The problem by the history

Today encountered a problem, that is, in the implementation of automated disaster preparedness, found that the original dead program is not completely closed, of course, This is not the focus of this article, the focus is this time, I have to shut it down completely, so I have this article.

second: Basic Knowledge2.1:java How to achieve

Java can acquire and delete applications launched by the Java virtual machine, but it does not provide APIs to get the API for other processes in the operating System.

however, Java can execute script commands for the operating System.

2.2: Find process based on port

This command is available in Windows

Netstat-ano   Viewing the process of all ports occupied by the operating system

  

" 8080 " get a process that occupies 80 ports

The results are as follows

Tcp127.0.0.1:51846        127.0.0.1:5037Time_wait0TCP127.0.0.1:51847        127.0.0.1:5037Time_wait0UDP0.0.0.0:4500*:*444UDP0.0.0.0:5355*:*1232

You can see that TCP/UPD is the protocol used, followed by the binding IP with the port, the last column, the process number (pid) that is Occupied.

2.3: Delete process based on process number

Let's see another order.

123

We can close the process number 123 process, of course, when I try the above command, the system prompt cannot terminate the process, then we can add a/F, as below, can be forcibly closed.

123

Three: Java implementation, support to kill multiple ports at once

As previously mentioned, Java can execute the operating system script, no matter what the operation of the system, then we can use this method to directly execute these commands to achieve the corresponding Effect.

 packagekill.window;Importjava.io.BufferedReader;Importjava.io.IOException;Importjava.io.InputStream;Importjava.io.InputStreamReader;Importjava.util.ArrayList;Importjava.util.HashSet;Importjava.util.List;Importjava.util.Scanner;Importjava.util.Set;Importjava.util.regex.Matcher;Importjava.util.regex.Pattern; public classKillserver {PrivateSet<integer>ports;  public Static voidMain (string[] Args)throwsinterruptedexception {System.out.println ("please Enter the port number of the Windows process you want to kill, and if there are more than one, comma separated"); System.out.println ("please input Kill port"); Scanner Scanner=NewScanner (system.in); String input=Scanner.next ();        Scanner.close (); string[] Split= Input.split (","); Set<Integer> ports =NewHashset<>();  for(String Spid:split) {Try{                intPID =Integer.parseint (spid);            Ports.add (pid); }Catch(Exception e) {System.out.println ("the wrong Port number, Please enter one or more ports, separated by commas"); Try{thread.sleep (5000); } Catch(interruptedexception e1) {e1.printstacktrace (); } system.exit (0); }} Killserver Kill=NewKillserver (); Kill.ports=ports; System.out.println ("need kill" + ports.size () + "num");  for(Integer pid:ports) {kill.start (pid); } System.out.println ("clean up, program is about to exit"); System.out.println ("SUCCESS"); Thread.Sleep (5000); System.exit (0); }         public voidStartintport) {runtime Runtime=Runtime.getruntime (); Try {            //Find Process NumberProcess p = runtime.exec ("cmd/c Netstat-ano | findstr \ "" +port+ "\" "); InputStream InputStream=P.getinputstream (); List<String> Read = Read (inputstream, "UTF-8"); if(read.size () = = 0) {System.out.println ("process not found for this port"); Try{thread.sleep (6000); System.exit (0); } Catch(interruptedexception E) {e.printstacktrace (); }            }Else{                 for(string string:read) {System.out.println (string); } System.out.println ("found" +read.size () + "process, preparing for cleanup");            Kill (read); }        } Catch(ioexception E) {e.printstacktrace (); }     }        /*** Verify that this line is the specified port, because the findstr command will find the included, for example, find Port 80, but will find out 8099 *@paramSTR *@return     */    Private Booleanvalidport (String str) {pattern pattern= Pattern.compile ("^ *[a-za-z]+ +\\s+"); Matcher Matcher=Pattern.matcher (str);        Matcher.find (); String Find=Matcher.group (); intSpstart = Find.lastindexof (":"); Find= find.substring (spstart + 1); intPort = 0; Try{port=Integer.parseint (find); } Catch(numberformatexception e) {System.out.println ("find the wrong port:" +find); return false; }        if( this. Ports.contains (port)) {            return true; }Else{            return false; }    }        /*** Replace with a set to remove the repetitive PID value *@paramData*/     public voidKill (list<string>Data) {Set<Integer> PIDs =NewHashset<>();  for(String Line:data) {intoffset = Line.lastindexof (""); String spid=line.substring (offset); SPID= Spid.replaceall ("", "" "); intPID = 0; Try{pid=Integer.parseint (spid); } Catch(numberformatexception e) {System.out.println ("get the process number error:" +spid);        } Pids.add (pid);    } killwithpid (pids); }        /*** Kill all ports at once *@paramPIDs*/     public voidKillwithpid (set<integer>Pids) {         for(Integer Pid:pids) {Try{process Process= Runtime.getruntime (). exec ("taskkill/f/pid" +pid+ ""); InputStream InputStream=Process.getinputstream (); String txt= Readtxt (inputstream, "GBK");            System.out.println (txt); } Catch(ioexception E) {e.printstacktrace (); }        }    }            Privatelist<string> Read (inputstream in,string charset)throwsioexception{List<String> data =NewArraylist<>(); BufferedReader Reader=NewBufferedReader (NewInputStreamReader (in, charset));        String line;  while(line = Reader.readline ())! =NULL){            BooleanValidport =Validport (line); if(validport) {data.add (line);        }} Reader.close (); returndata; }     publicString readtxt (inputstream in,string Charset)throwsIoexception{bufferedreader Reader=NewBufferedReader (NewInputStreamReader (in, charset)); StringBuffer SB=NewStringBuffer ();        String line;  while(line = Reader.readline ())! =NULL) {sb.append (line);        } reader.close (); returnsb.tostring (); }}

Use Java code to close the specified port under Program-windows

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.