Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 359
thetna Avatar asked Apr 29 '12 17:04

thetna


People also ask

Can BufferedReader read string?

2.3. BufferedReader is synchronized (thread-safe) while Scanner is not. Scanner can parse primitive types and strings using regular expressions.

What is the return type of read () method in BufferedReader class?

The read() method of a Java BufferedReader returns an int which contains the char value of the next character read. If the read() method returns -1, there is no more data to read in the BufferedReader , and it can be closed.

What is the function of read () and readLine () method of the BufferedReader class?

This class provides a method named read() and readLine() which reads and returns the character and next line from the source (respectively) and returns them. Instantiate an InputStreamReader class bypassing your InputStream object as a parameter.

What is readLine () in Java?

The readLine() method of Console class in Java is used to read a single line of text from the console. Syntax: public String readLine() Parameters: This method does not accept any parameter. Return value: This method returns the string containing the line that is read from the console.


2 Answers

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)

like image 117
amit Avatar answered Sep 25 '22 13:09

amit


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);
}
like image 22
Peter Lawrey Avatar answered Sep 26 '22 13:09

Peter Lawrey