简体   繁体   English

java bufferedReader。 如何读取行的一部分

[英]java bufferedReader. how to read parts of a line

Ok now, here's my question. 好吧,这是我的问题。 I wrote an algorithm to do specific things. 我写了一种算法来做特定的事情。 Currently I create my processes myself in the class constructor and store them in a priority queue. 当前,我自己在类构造函数中创建进程并将它们存储在优先级队列中。 However I want to be able to write a .txt file with multiple lines. 但是我希望能够编写多行的.txt文件。 Each line will represent a process with its different attributes separated by space. 每行将代表一个进程,其不同属性之间用空格隔开。 Here's what my .txt will look like: 这是我的.txt的样子:

P1 0 8
P2 1 4
P3 2 9
P4 3 3
END 4 9999

p1, p2... etc are the names of each process. p1,p2 ...等是每个进程的名称。 Then the second column is the first attribute and the third column is the second attribute. 那么第二列是第一属性,第三列是第二属性。

I need to be able to read each column at a time and store the value in my processes. 我需要能够一次读取每一列,并将值存储在我的流程中。 How can I read those values and distinguish between them? 如何读取这些值并加以区分? (treat them as separate things) (将它们作为单独的东西处理)

So you want to read the file line-by-line and separate each line? 因此,您想逐行读取文件并分开每一行吗?

BufferReader in=new BufferedReader...
String line;
while ((line=in.readLine())!=null) {
  String[] data=line.split(" ");
  //now, data will be a array which contains the data
  //data[0] = the first item in the line
  //data[1] = the first number
  //data[2] = the second number
}

Have a look at the java.util.Scanner class, it can help to read separate tokens from a Reader . 看看java.util.Scanner类,它可以帮助从Reader读取单独的标记。

It has methods to read the next token as an integer, as a string or many other types. 它具有将下一个标记读取为整数,字符串或许多其他类型的方法。 There are also some examples in the class Javadoc... Javadoc类中也有一些示例...

You got both whitespace (seperating the attributes) and new line (seperates the whole process information) as seperators. 您同时获得了空格(分隔属性)和换行(分隔整个过程信息)作为分隔符。

Using a BufferedReader, you could either read a whole line (reader.readLine()) to parse one whole process information and use String.split() to seperate the attributes (edit: see answer from dyslabs). 使用BufferedReader,您可以读取整行(reader.readLine())来解析整个过程信息,并可以使用String.split()来分隔属性(编辑:请参见dyslabs的答案)。

An obviously more performant (but less intuitive) approach is to read single characters (reader.read()) and check if you either read a whitespace- or a new-line-character: 一种明显更高效(但不太直观)的方法是读取单个字符(reader.read())并检查是否读取了空白字符或换行符:

// caution: code is not tested but shows the general approach
List<ProcessInformation> processInfo = new ArrayList<>();
String pInfoStr = new String[3];

int processInfoIndex = 0;
String[] processInfoHolder = new String[3];
String processInfo = "";
int c;
while( (c = reader.read()) != -1 ) {
   if (Character.isWhitespace(c)) {
      processInfoHolder[processInfoIndex++] = processInfo;
      processInfoStr = "";
   }
   else if (c == 10) { // not sure if correct codepoint for whitespace
      processInfo.add(new ProcessInfo(processInfoHolder));
      processInfoIndex = 0;
   }
   else {
      processInfoStr += c;
   }
}

You could even more optimize this method by using StringBuilder. 您可以使用StringBuilder进一步优化此方法。

In order to be able to read a file line by line I use readLine() != null while in order to retrieve the values separated by whitespace, use the split method and store each value of a single line in an array, here's how I implemented your example: 为了能够逐行读取文件,我使用readLine()!= null,而为了检索由空格分隔的值,请使用split方法并将一行的每个值存储在数组中,这就是我的方法实现了您的示例:

public static void main(String[] args) {
    // TODO Auto-generated method stub
    BufferedReader buffer;
    FileReader fileReader;
    String p1[] = new String[4];
    String p2[] = new String[4];
    String p3[] = new String[4];
    String p4[] = new String[4];
    String end[] = new String[4];
    try {
        fileReader = new FileReader(new File("file.txt"));
        buffer = new BufferedReader(fileReader);
        String line;
        line = buffer.readLine();
        // ============= Read the fist line =============
        p1 = line.split("\\s+");

        while((line = buffer.readLine()) != null) {

            // ============= Read the second line =============
            p2 = line.split("\\s+");        

            // ============= Read the third line =============
            if((line = buffer.readLine()) != null) {
                p3 = line.split("\\s+");        
            }
            // ============= Read the forth line =============
            if((line = buffer.readLine()) != null) {
                p4 = line.split("\\s+");        
            }
            // ============= Read the last line =============
            if((line = buffer.readLine()) != null) {
                end = line.split("\\s+");       
            }

        }
        fileReader.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 

    int v1[] = new int[3];
    int v2[] = new int[3];
    int v3[] = new int[3];
    int v4[] = new int[3];
    int v_end[] = new int[3];


    for (int i = 0 ; i < p1.length; i++)
        System.out.print(p1[i]+ " ");
    System.out.println();
    for (int i = 0 ; i < p2.length; i++)
        System.out.print(p2[i]+ " ");
    System.out.println();
    for (int i = 0 ; i < p3.length; i++)
        System.out.print(p3[i]+ " ");
    System.out.println();
    for (int i = 0 ; i < p4.length; i++)
        System.out.print(p4[i]+ " ");
    System.out.println();
    for (int i = 0 ; i < end.length; i++)
        System.out.print(end[i]+ " ");
}

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

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