1

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
4
  • 3
    A line with a line break inside it is not one line, it is two lines. Commented Feb 20, 2015 at 19:26
  • You could ecape the embedded line breaks. If not, you have to parse the line. Commented Feb 20, 2015 at 19:37
  • How can you tell the embedded linebreaks apart from the "real" linebreaks? Commented Feb 20, 2015 at 19:41
  • Do you control the format of the file? It would be much more useful to have a delimiter which is never part of the actual question. For e.g. a special char like ~. Best would be to have a proper text format like TSV (tab separated file) or a YAML file... Commented Feb 20, 2015 at 20:13

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.