子字符串索引超出Java的范围

问题描述 投票:1回答:3

我正在编写一个简单的代码,使用Java中的tasklist仅显示“ console”类型的进程的name

由于此代码中的字符串索引超出范围错误,我无法这样做。我使用索引36到43,因为在这些代码中,我在输出代码的过程中得到了进程类型,在这里我们使用tasklist打印所有进程。进程名称的0到30相同。

请帮助我。

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();
     }
}

}

java process substring tasklist stringindexoutofbounds
3个回答
0
投票

为了避免Index超出范围,我应该首先检查当前行是否包含单词“ Console”,还要检查长度:

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();
     }
}}

2
投票

尝试检查该行的长度。可能时间不够长,因为时间不够长,这会导致超出范围的错误。

 System.out.println(line.length());

或者您可以在通话前检查线路的长度

 if (line.length() >= 43){
 ....

0
投票

我看到的是,任务列表的开头是空行。在while循环开始时,简单检查是if (!line.contains("Console")) continue;。这样,您将跳过每一行,其中不包含字符串Console。

© www.soinside.com 2019 - 2024. All rights reserved.