Java.io.LineNumberReader.read() Method

Advertisements


Description

The java.io.LineNumberReader.read(char[] cbuf, int off, int len) method reads characters into a portion of an array.

Declaration

Following is the declaration for java.io.LineNumberReader.read(char[] cbuf, int off, int len) method:

public int read(char[] cbuf, int off, int len)

Parameters

  • cbuf -- destination character buffer

  • off -- offset at which to start storing characters

  • len -- maximum number of characters to read

Return Value

The method returns the number of bytes read, or -1 if the end of the stream has already been reached.

Exception

  • IOException -- If an I/O error occurs

Example

The following example shows the usage of java.io.LineNumberReader.read(char[] cbuf, int off, int len) method.

package com.tutorialspoint;

import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;

public class LineNumberReaderDemo {
   public static void main(String[] args) throws IOException {
      
      FileReader fr = null;
      LineNumberReader lnr = null;
      int i;
      char[] cbuf = new char[5];
      
      try{
         // create new reader
         fr = new FileReader("C:/test.txt");
         lnr = new LineNumberReader(fr);
         
         // read characters into the buffer
         i=lnr.read(cbuf, 2, 3);
         System.out.println("Number of char read: "+i);
         
         // for each character in the buffer
         for(char c:cbuf)
         {
            // if char is empty
            if((int)c==0)
               c='-';
            
            // prints char
            System.out.print(c);
         }
      }catch(Exception e){
         
         // if any error occurs
         e.printStackTrace();
      }finally{
         
         // closes the stream and releases system resources
         if(fr!=null)
            fr.close();
         if(lnr!=null)
            lnr.close();
      }
   }
}

Assuming we have a text file c:/test.txt, which has the following content. This file will be used as an input for our example program:

ABCDE

Let us compile and run the above program, this will produce the following result:

Number of char read: 3
--ABC



Advertisements
Advertisements