I am writing a simple code that displays only the name of the processes which are of "console" type using tasklist in java.
I am unable to do so because of the string index out of bounds error in this code. I used index 36 to 43 because in these I got the process type during output of the code where we print all the processes using tasklist. Same goes for 0 to 30 for process name.
Please help me with this.
import java.io.*;
public class process_name
{
public static void main(String []args)
{
try {
int i;
String line,pn,pt;
pn="";
Process p = Runtime.getRuntime().exec(System.getenv("windir") +"\\system32\\"+"tasklist.exe");
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null)
{
pt=line.substring(36,43);
if(pt.equals("Console"))
{
pn=line.substring(0,30);
System.out.println(pn);
}
System.out.println();
}
input.close();
}
catch (Exception err)
{
err.printStackTrace();
}
}
}
Try checking the length of that line. It might not be long enough which causes an out of bounds error as it is not long enough.
System.out.println(line.length());
or you could check the length of the line before the call
if (line.length() >= 43){
....
What I can see, tasklist prints at the beginning an empty line. An easy check would be if (.line;contains("Console")) continue;
at the beginning of the while loop. With that, you skip every line, which does not contain the string Console.
Just to avoid the Index to be out of bounds, I should check first if the current line contains the word "Console" and also check the length:
import java.io.*;
public class Main
{
public static void main(String []args)
{
try {
int i;
String line,pn,pt;
pn="";
Process p = Runtime.getRuntime().exec(System.getenv("windir") +"\\system32\\"+"tasklist.exe");
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null)
{
if(line.contains("Console"))
{
if(line.length()>30){
pn=line.substring(0,30); System.out.println(pn);}
}
System.out.println();
}
input.close();
}
catch (Exception err)
{
err.printStackTrace();
}
}}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.