BufferedReader to read lines, then assign the new

2019-08-08 12:27发布

问题:

I have a text file that I need to modify before parsing it. 1) I need to combine lines if leading line ends with "\" and delete white spaced line. this has been done using this code

public List<String> OpenFile() throws IOException {
        try (BufferedReader br = new BufferedReader(new FileReader(path))) {
            String line;
            StringBuilder concatenatedLine = new StringBuilder();
            List<String> formattedStrings = new ArrayList<>();
            while ((line = br.readLine()) != null) {

                if (line.isEmpty()) {
                    line = line.trim();

                } else if (line.charAt(line.length() - 1) == '\\') {
                   line = line.substring(0, line.length() - 1);
                   concatenatedLine.append(line);
                }  else {
                    concatenatedLine.append(line);
                    formattedStrings.add(concatenatedLine.toString());
                    concatenatedLine.setLength(0);
                }
            }
            return formattedStrings;
        }

    }
}//The formattedStrings arrayList contains all of the strings formatted for use.

Now My question, how can I search those lines for pattern and assign their token[i] to variables that I can call or use later.

the New combined text will look like this:

Field-1 Field-2 Field-3 Field-4 Field-5 Field-6 Field-7 

Now, if the line contains "Field-6" and "Field-2" Then set the following:

String S =token[1] token[3]; 
String Y =token[5-7];

Question you might have for me, how am I deciding on which token to save to a string? I will manually search for the pattern in the text file and if the "Line contain Field-6 and Field-2 or any other required pattern. Then manually count which token I need to assign to the string. However, it will be nice if there is another way to approach this, for ex assign what's in between token[4] and token[7] to string (s) if the line has token[2] and token[6]. or another way that provides more Granule Control over what to store as string and what to ignore.