简体   繁体   中英

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. Each line will represent a process with its different attributes separated by space. Here's what my .txt will look like:

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

p1, p2... etc are the names of each process. 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 .

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...

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).

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:

// 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.

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:

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]+ " ");
}

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.

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