简体   繁体   English

如何从Java中的txt文件获取特定行

[英]How to get specific line from a txt file in java

I'm dumping info about all the processes running on my pc into a .txt file. 我正在将PC上正在运行的所有进程的信息转储到.txt文件中。 To do this I execute handle.exe from my java application. 为此,我从我的Java应用程序执行handle.exe。 The file contains all the running processes in this format: 该文件包含此格式的所有正在运行的进程:

RuntimeBroker.exe pid: 4756 
4: Key           HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image 
8: Event  
   10: WaitCompletionPacket 
   1C: IRTimer       
   20: WaitCompletionPacket 
   24: IRTimer       
   28: File          \Device\CNG

--

SearchIndexer.exe pid: 5616 
4: Event         
8: WaitCompletionPacket 
C: IoCompletion  
1C: IRTimer
20: File          \Device\0000007s
22: Directory   

I need to get the name of the process that is using a given device ie if I'm looping through the file searching for the string "\\Device\\0000007s", I need to get the name of the process and the process id which is a few lines above. 我需要获取正在使用给定设备的进程的名称,即,如果我遍历文件搜索字符串“ \\ Device \\ 0000007s”,则需要获取进程的名称和进程ID,即上面几行。 Does anybody know how could I do this? 有人知道我该怎么做吗? The processes are delimited by a line of dashes -- in the file. 进程由短划线分隔-在文件中。 Bear in mind that the file is massive, this is just an example. 请记住,文件很大,这只是一个例子。

I would read each line of a process (using a Scanner ) into a List<String> . 我会将进程的每一行(使用Scanner )读入List<String> Then search through the List<String> for your desired String and if it is there, do your processing. 然后在List<String>搜索所需的String ,如果存在,则进行处理。 Here is some psuedo-code: 这是一些伪代码:

Scanner scanner = new Scanner("path/to/file.txt");
List<String> stringList;
while(scanner.hasNextLine()) {
  String nextLine = scanner.nextLine();

  if(nextLine.equals("--") {
    for(String line : stringList) {
      if(line.contains("\Device\0000007s") {
        // Do your processsing here
      }
    }

    stringList.clear();
  }

  else {
    stringList.add(nextLine);
  }

}

This is just psuedo-code, doesn't handle the edge case of the last process and probably won't compile. 这只是伪代码,不处理最后一个过程的边缘情况,可能无法编译。 I will leave the nitty-gritty syntax up to you. 我将让您掌握具体的语法。

There is probably a more optimal way of doing this, with less looping. 这样做可能是更理想的方式,而且循环更少。 But for simple things like this I much prefer a clear approach to an optimized one. 但是对于像这样的简单事情,我更喜欢采用清晰的方法来进行优化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM