简体   繁体   中英

Java reading a line with multiple line breaks within

I have a file with three lines in. I want to read in each line into a string. Im planning on using the java buffered reader

I thought i'd do a while loop that reads a line until it reaches end of the line (\\n) then store that into a variables and continue until EOF is reached.

Reason why this won't be a duplicate question is my text file has loads of \\n within it per line. As seen below. How would I then be able to read a line and store it into a string. The line breaks are needed as the display requires the option to be on its own line

example.txt

Q1: (A + B)*(A+B) \n 1. A*A + B*B \n 2. A*A +A*B + B*B \n 3. A*A +2*A*B + B*B \n
Q2: (A + B)*(A - B) \n 1. A*A + 2*B*B \n 2. A*A - B*B \n 3. A*A -2*A*B + B*B \n
Q3: sin(x)*sin(x) + cos(x)*cos(x) \n 1. 1 \n 2. 2 \n 3. 3 \n

As @Jesper mentioned in the comments your definion of a line is a bit off. Your best bet is to read in multiple lines until you find a delimiter that your looking for. In this case it seem like you should be looking for Q followed by a number and a colon.

if reading everything in at once is not a problem you can even do something like this.

fullString.split("(?<=Q\\d:)");

The resulting array will each contain a single question, assuming your text does not contain Q#: somewhere in it.

You can use Scanner class's useDelimiter method. Like this:

Scanner scanner = new Scanner(new File("example.txt"));
scanner.useDelimiter("Q");
while (scanner.hasNext()) {
    String line[i++] = scanner.next();
}

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