Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Java.io.PushbackInputStream class in Java
Next article icon

Java.io.LineNumberInputStream Class in Java

Last Updated : 23 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

java.io.LineNumberInputStream class is simply an extension of input stream providing a extra facility to keep the record of current line number. 

Line is a sequence of bytes ending with : ‘\r’ i.e. a carriage return character or a newline character : ‘\n’, or a linefeed character following the carriage return character.

Declaration :  

public class LineNumberInputStream    extends Reader

Constructors :  

LineNumberInputStream(InputStream in) :  Constructs a newline no. stream that reads  it's input from the specified Input Stream.

Methods:  

LineNumberInputStream Class

  • read() : java.io.LineNumberInputStream.read() reads next byte of data from input stream. It returns int value representing the bytes in the range of ‘0 – 255’. It returns ‘-1’ to indicate end of Input Stream. 
    Syntax : 
public int read() Parameters :  ------- Return :  int value representing the bytes in the range of '0 - 255'. return -1, indicating end of Input Stream. Exception:  IOException : in case I/O error occurs

Implementation : 

Java




// Java program illustrating the working of read() method
 
import java.io.*;
 
public class NewClass
{
    public static void main(String[] args) throws IOException
    {
        // LineNumberInputStream & FileInputStream initially null
        LineNumberInputStream geekline = null;
        FileInputStream geekinput = null;
 
        try{
            char c;
            int a;
 
            // New InputStream : 'ABC' is created
            geekinput = new FileInputStream("ABC.txt");
            geekline = new LineNumberInputStream(geekinput);
 
            // read() method returning Bytes of Input Stream as integer
            // '-1' indicating to read till end Of Input Stream
            while((a = geekline.read()) != -1)
            {
                // Since read() method returns Integer value
                // So, we convert each integer value to char
                c = (char)a;
                System.out.print(c);
            }
        }
        catch(Exception e)
        {
            // In case of error
            e.printStackTrace();
            System.out.println("ERROR Occurs ");
        }
        finally
       {
            // Closing the streams, Once the End of Input Stream is reached
            if(geekinput != null)
                geekinput.close();
 
            if(geekline != null)
                geekline.close();
        }
    }
}
 
 

Note : 
The following Java Code won’t run here as we can’t access any file on online IDE. 
So, copy the program to your system and run it there.

The ABC.txt file used in the program contains : 

Hello Geeks. Explaining  read() method

Output : 

Hello Geeks. Explaining  read() method
  • getLineNumber() : java.io.LineNumberInputStream.getLineNumber() returns number of current line. 
    Syntax : 
 public int getLineNumber() Parameters :  ------- Return :  no. of current line

Implementation : 

Java




// Java program illustrating the working of getLineNumber() method
 
import java.io.*;
 
public class NewClass
{
    public static void main(String[] args) throws IOException
    {
        // LineNumberInputStream & FileInputStream initially null
        LineNumberInputStream geekline = null;
        FileInputStream geekinput = null;
 
        try
           {
            char c;
            int a, b;
 
            // New InputStream : 'ABC' is created
            geekinput = new FileInputStream("ABC.txt");
            geekline = new LineNumberInputStream(geekinput);
 
            while((a = geekline.read()) != -1)
            {
                // So, we convert each integer value to char
                c = (char)a;
                 
                // Use of getLineNumber() : to print line no.
                a = geekline.getLineNumber();
                System.out.println(" At line : " + a);
                System.out.print(c);
 
            }
            a = geekline.getLineNumber();
            System.out.println(" at line: " + a);
 
        }
        catch(Exception e)
        {
            // In case of error
            e.printStackTrace();
            System.out.println("ERROR Occurs ");
        }
        finally
        {
            // Closing the streams, Once the End of Input Stream is reached
            if(geekinput != null)
                geekinput.close();
            if(geekline != null)
                geekline.close();
        }
    }
}
 
 

Note : 
The following Java Code won’t run here as we can’t access any file on online IDE. 
So, copy the program to your system and run it there.

The ABC.txt file used in the program contains : 

no. of lines

Output : 

 At line : 0 n At line : 0 o At line : 0 . At line : 0   At line : 0 o At line : 0 f At line : 1   At line : 1 l At line : 1 i At line : 1 n At line : 1 e At line : 1 s at line: 1
  • available() : java.io.LineNumberInputStream.available() returns the number of bytes that can be read from the Input Stream without blocking. 
    Syntax : 
public int available() Parameters :  ------- Return :  returns the no. of bytes that can be read from the Input Stream. Exception:  IOException : in case I/O error occurs

Implementation : 

Java




// Java program illustrating the working of available() method
 
import java.io.*;
 
public class NewClass
{
    public static void main(String[] args) throws IOException
    {
        // LineNumberInputStream & FileInputStream initially null
        LineNumberInputStream geekline = null;
        FileInputStream geekinput = null;
 
        try{
            char c;
            int a, b;
 
            // New InputStream : 'ABC' is created
            geekinput = new FileInputStream("ABC.txt");
            geekline = new LineNumberInputStream(geekinput);
 
            while((a = geekline.read()) != -1)
            {
              // So, we convert each integer value to char
                c = (char)a;
 
              // Use of available method : return no. of bytes that can be read
                a = geekline.available();
                System.out.println(c + " Bytes available : " + a);
 
            }
 
        }
        catch(Exception e)
        {
            // In case of error
            e.printStackTrace();
            System.out.println("ERROR Occurs ");
        }
        finally
        {
            // Closing the streams, Once the End of Input Stream is reached
            if(geekinput != null)
                geekinput.close();
 
            if(geekline != null)
                geekline.close();
        }
    }
}
 
 

Note : 
The following Java Code won’t run here as we can’t access any file on online IDE. 
So, copy the program to your system and run it there.

The ABC.txt file used in the program contains : 

available

Output : 

a Bytes available : 4 v Bytes available : 3 a Bytes available : 3 i Bytes available : 2 l Bytes available : 2 a Bytes available : 1 b Bytes available : 1 l Bytes available : 0 e Bytes available : 0
  • setLineNumber() : java.io.LineNumberInputStream.setLineNumber(int arg) assigns line number to the argument we want. 
    Syntax : 
public void setLineNumber(int arg) Parameters :  arg : line number to assign Return :  void Exception:  -----

Implementation : 

Java




// Java program illustrating the working of setLineNumber() method
 
import java.io.*;
 
public class NewClass
{
    public static void main(String[] args) throws IOException
    {
        // LineNumberInputStream & FileInputStream initially null
        LineNumberInputStream geekline = null;
        FileInputStream geekinput = null;
 
        try{
            char c;
            int a, b = 0;
 
            // New InputStream : 'ABC' is created
            geekinput = new FileInputStream("ABC.txt");
            geekline = new LineNumberInputStream(geekinput);
 
            while((a = geekline.read()) != -1)
            {
                // So, we convert each integer value to char
                c = (char)a;
                 
                // Use of setLineNumber() : to set the line no.
                geekline.setLineNumber(100 + b);
 
                // getLineNumber() : returning the current line no.
                a = geekline.getLineNumber();
                System.out.println(c + " Line No. Set : " + a);
                b++;
            }
        }
        catch(Exception e)
        {
            // In case of error
            e.printStackTrace();
            System.out.println("ERROR Occurs ");
        }
        finally
        {
            // Closing the streams, Once the End of Input Stream is reached
            if(geekinput != null)
                geekinput.close();
 
            if(geekline != null)
                geekline.close();
        }
    }
}
 
 

Note : 
The following Java Code won’t run here as we can’t access any file on online IDE. 
So, copy the program to your system and run it there.

The ABC.txt file used in the program contains : 

LineNumber

Output : 

L Line No. Set : 100 i Line No. Set : 101 n Line No. Set : 102 e Line No. Set : 103 N Line No. Set : 104 u Line No. Set : 105 m Line No. Set : 106 b Line No. Set : 107 e Line No. Set : 108 r Line No. Set : 109
  • skip() : java.io.LineNumberInputStream.skip(long arg) skips and discards ‘arg’ bytes from Input Stream data. The skip method of LineNumberInputStream creates a byte array and then repeatedly reads into it until n bytes have been read or the end of the stream has been reached. 
    Syntax : 
public long skip(long arg) Parameters :  arg : no. of bytes of Input Stream data to skip. Return :  no. of bytes to be skipped Exception:  IOException : in case I/O error occurs

Implementation : 

Java




// Java program illustrating the working of setLineNumber() method
 
import java.io.*;
 
public class NewClass
{
    public static void main(String[] args) throws IOException
    {
        // LineNumberInputStream & FileInputStream initially null
        LineNumberInputStream geekline = null;
        FileInputStream geekinput = null;
 
        try{
            char c;
            int a, b = 0;
 
            // New InputStream : 'ABC' is created
            geekinput = new FileInputStream("ABC.txt");
            geekline = new LineNumberInputStream(geekinput);
 
            while((a = geekline.read()) != -1)
            {
                // So, we convert each integer value to char
                c = (char)a;
 
                // skip() : to skip and discard 'arg' bytes
                // Here skip() will skip and discard 3 bytes.
                geekline.skip(3);
                System.out.println(c);
            }
        }
        catch(Exception e)
        {
            // In case of error
            e.printStackTrace();
            System.out.println("ERROR Occurs ");
        }
        finally{
            // Closing the streams, Once the End of Input Stream is reached
            if(geekinput != null)
                geekinput.close();
            if(geekline != null)
                geekline.close();
        }
    }
}
 
 

Note : 
The following Java Code won’t run here as we can’t access any file on online IDE. 
So, copy the program to your system and run it there.

The ABC.txt file used in the program contains : 

Program Explaining Skip() method

Output :” 

P r E a n k ) t
  • read() : java.io.LineNumberInputStream.read(byte[] buffer, int offset, int maxlen) reads up to ‘maxlen’ bytes from Input Stream into bytes. 
    Syntax : 
public int read(byte[] buffer, int offset, int maxlen) Parameters :  buffer : buffer whose data to read offset : starting offset of the data maxlen : max. no. of bytes to read Return :  total no. of bytes, else return -1 if End of Input Stream is identified Exception:  IOException : in case I/O error occurs

Implementation : 

Java




// Java program illustrating the working of read() method
 
import java.io.*;
 
public class NewClass
{
    public static void main(String[] args) throws IOException
    {
        // LineNumberInputStream & FileInputStream initially null
        LineNumberInputStream geekline = null;
        FileInputStream geekinput = null;
 
        try{
            char c;
            int a;
 
            // New InputStream : 'ABC' is created
            geekinput = new FileInputStream("ABC.txt");
            geekline = new LineNumberInputStream(geekinput);
 
            // read() method returning Bytes of Input Stream as integer
            // '-1' indicating to read till end Of Input Stream
            while((a=geekline.read())!=-1)
            {
                // Since read() method returns Integer value
                // So, we convert each integer value to char
                c = (char)a;
                System.out.print(c);
            }
        }
        catch(Exception e)
        {
            // In case of error
            e.printStackTrace();
            System.out.println("ERROR Occurs ");
        }
        finally
       {
            // Closing the streams, Once the End of Input Stream is reached
            if(geekinput != null)
                geekinput.close();
 
            if(geekline != null)
                geekline.close();
        }
    }
}
 
 

Note : 
The following Java Code won’t run here as we can’t access any file on online IDE. 
So, copy the program to your system and run it there.

The ABC.txt file used in the program contains : 

Read() method

what the method does is offset = r and maxlen = 5… so —i.e. 3 offset, then 5 bytes i.e. Read(, then again offset, so — 
Output : 

The number of char read: 5  ---Read(--
  • mark() : Java.io.LineNumberInputStream.mark(int arg) marks the current position of the input stream. It sets readlimit i.e. maximum number of bytes that can be read before mark position becomes invalid. 
    Syntax :
public void mark(int arg) Parameters : arg : integer specifying the read limit of the input Stream Return :  void
  • reset() : Java.io.LineNumberInputStream.reset() is invoked by mark() method. It re-positions the input stream to the marked position. 
    Syntax :
public void reset() Parameters : ---- Return :  void Exception : ->  IOException : If I/O error occurs.

Java Program explaining LineNumberInputStream Class methods : reset() and mark() 

Java




// Java program illustrating the working of LineNumberInputStream method
// mark() and reset()
 
import java.io.*;
 
public class NewClass
{
    public static void main(String[] args) throws Exception
    {
 
        LineNumberInputStream geekline = null;
        FileInputStream geek = null;
        try{
 
            geek = new FileInputStream("GEEKS.txt");
            geekline = new LineNumberInputStream(geek);
 
            // read() method : reading and printing Characters one by one
            System.out.println("Char : " + (char)geekline.read());
            System.out.println("Char : " + (char)geekline.read());
            System.out.println("Char : " + (char)geekline.read());
 
            // mark() : read limiting the 'geek' input stream
            geekline.mark(0);
 
            // skip() : it results in reading of 'e' in G'e'eeks
            geekline.skip(1);
            System.out.println("skip() method comes to play");
            System.out.println("mark() method comes to play");
            System.out.println("Char : " + (char)geekline.read());
            System.out.println("Char : " + (char)geekline.read());
            System.out.println("Char : " + (char)geekline.read());
 
            boolean check = geekline.markSupported();
            if(geekline.markSupported())
            {
                // reset() method : repositioning the stream to marked positions.
                geekline.reset();
                System.out.println("reset() invoked");
                System.out.println("Char : " + (char)geekline.read());
                System.out.println("Char : " + (char)geekline.read());
            }
            else
            {
                System.out.println("reset() method not supported.");
            }
 
            System.out.println("geekline.markSupported() supported reset() : "
                                                        + check);
 
        }
        catch(Exception except)
        {
 
            // in case of I/O error
            except.printStackTrace();
        }
        finally
        {
            // releasing the resources back to the GarbageCollector when closes
            if(geek != null)
                geek.close();
 
            if(geekline != null)
                geekline.close();
        }
    }
}
 
 

Note : 
This code won’t run on online IDE as no such file is present here. 
You can run this code on your System to check the working. 

ABC.txt file used in the code has 

HelloGeeks

Output : 

Char : H Char : e Char : l skip() method comes to play mark() method comes to play Char : o Char : G Char : e reset() method not supported. geekline.markSupported() supported reset() : false

 

 



Next Article
Java.io.PushbackInputStream class in Java

M

Mohit Gupta
Improve
Article Tags :
  • Java
Practice Tags :
  • Java

Similar Reads

  • Java.io.LineNumberReader class in Java
    A buffered character-input stream that keeps track of line numbers. This class defines methods setLineNumber(int) and getLineNumber() for setting and getting the current line number respectively. By default, line numbering begins at 0. This number increments at every line terminator as the data is r
    4 min read
  • Java.io.PipedInputStream class in Java
    Pipes in IO provides a link between two threads running in JVM at the same time. So, Pipes are used both as source or destination. PipedInputStream is also piped with PipedOutputStream. So, data can be written using PipedOutputStream and can be written using PipedInputStream.But, using both threads
    5 min read
  • Java.io.OutputStream class in Java
    This abstract class is the superclass of all classes representing an output stream of bytes. An output stream accepts output bytes and sends them to some sink. Applications that need to define a subclass of OutputStream must always provide at least a method that writes one byte of output. Constructo
    2 min read
  • Java.io.PushbackInputStream class in Java
    Pushback is used on an input stream to allow a byte to be read and then returned (i.e, "pushed back") to the stream. The PushbackInputStream class implements this idea. It provides a mechanism "peek" at what is coming from an input stream without disrupting it. It extends FilterInputStream.Fields: p
    7 min read
  • Java.io.ObjectInputStream Class in Java | Set 2
    Java.io.ObjectInputStream Class in Java | Set 1 Note : Java codes mentioned in this article won't run on Online IDE as the file used in the code doesn't exists online. So, to verify the working of the codes, you can copy them to your System and can run it over there. More Methods of ObjectInputStrea
    6 min read
  • Java.io.ObjectInputStream Class in Java | Set 1
    ObjectInputStream Class deserializes the primitive data and objects previously written by ObjectOutputStream. Both ObjectOutputStream and ObjectInputStream are used as it provides storage for graphs of object.It ensures that the object it is working for, matches the classes of JVM i.e Java Virtual M
    9 min read
  • Java.io.Printstream Class in Java | Set 1
    A PrintStream adds functionality to another output stream, namely the ability to print representations of various data values conveniently. Unlike other output streams, a PrintStream never throws an IOException; instead, exceptional situations merely set an internal flag that can be tested via the c
    5 min read
  • Java.io.Printstream Class in Java | Set 2
    Java.io.Printstream Class in Java | Set 1More Methods: PrintStream printf(Locale l, String format, Object... args) : A convenience method to write a formatted string to this output stream using the specified format string and arguments. Syntax :public PrintStream printf(Locale l, String format, Obje
    6 min read
  • Java.io.SequenceInputStream in Java
    The SequenceInputStream class allows you to concatenate multiple InputStreams. It reads data of streams one by one. It starts out with an ordered collection of input streams and reads from the first one until end of file is reached, whereupon it reads from the second one, and so on, until end of fil
    3 min read
  • Java.util.zip.ZipInputStream class in Java
    This class implements an input stream filter for reading files in the ZIP file format. Includes support for both compressed and uncompressed entries. Constructors: ZipInputStream(InputStream in) : Creates a new ZIP input stream. ZipInputStream(InputStream in, Charset charset) : Creates a new ZIP inp
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences