thetna
thetna

Reputation: 7143

reading line in bufferedReader

From the javadoc

public String readLine()
            throws IOException

Read a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed. 

I have following kind of text :

Now the earth was formless and empty.  Darkness was on the surface
of the deep.  God's Spirit was hovering over the surface
of the waters.

I am reading lines as:

 while(buffer.readline() != null){
       }

But, the problem is it is considering a line for string upto before newline.But i would like to consider line when string ends with .. How would i do it?

Upvotes: 5

Views: 6266

Answers (4)

Peter Lawrey
Peter Lawrey

Reputation: 533432

You can read a character at a time, and copy the data to a StringBuilder

Reader reader = ...;
StringBuilder sb = new StringBuilder();
int ch;
while((ch = reader.read()) >= 0) {
    if(ch == '.') break;
    sb.append((char) ch);
}

Upvotes: 5

Thomas Uhrig
Thomas Uhrig

Reputation: 31605

You could split the whole text by every .:

String text = "Your test.";
String[] lines = text.split("\\.");

After you split the text you get an array of lines. You could also use a regex if you want more control, e.g. to split the text also by : or ;. Just google it.

PS.: Perhaps you have to remove the new line characters first with something like:

text = text.replaceAll("\n", "");

Upvotes: 4

amit
amit

Reputation: 178411

You can use a Scanner and set your own delimiter using useDelimiter(Pattern).

Note that the input delimiter is a regex, so you will need to provide the regex \. (you need to break the special meaning of the character . in regex)

Upvotes: 7

mata
mata

Reputation: 69012

  • Use a java.util.Scanner instead of a buffered reader, and set the delimiter to "\\." with Scanner.useDelimiter(). (but be aware that the delimiter is consumed, so you'll have to add it again!)
  • or read the raw string and split it on each .

Upvotes: 4

Related Questions