🔏
Tech
  • 🟢App aspects
    • Software architecture
      • Caching
      • Anti-patterns
      • System X-ability
      • Coupling
      • Event driven architecture
        • Command Query Responsibility Segregation (CQRS)
        • Change Data Capture (CDC)
      • Distributed transactions
      • App dev notes
        • Architecture MVP
      • TEMP. Check list
      • Hexagonal arch
      • Communication
        • REST vs messaging
        • gRPC
        • WebSocket
      • Load balancers
      • Storage limits
      • Event storming
    • Authentication
    • Deployment strategy
  • Databases
    • Classification
    • DB migration tools
    • PostreSQL
    • Decision guidance
    • Index
      • Hash indexes
      • SSTable, LSM-Trees
      • B-Tree
      • Engines, internals
    • Performance
  • System design
    • Interview preparation
      • Plan
        • Instagram
        • Tinder
        • Digital wallet
        • Dropbox
        • Live video streaming
        • Uber
        • Whatsup
        • Tiktok
        • Twitter
        • Proximity service
    • Algorithms
    • Acronyms
  • 🟢Programming languages
    • Java
      • Features
        • Field hiding
        • HashCode() and Equals()
        • Reference types
        • Pass by value
        • Atomic variables
      • Types
      • IO / NIO
        • Java NIO
          • Buffer
          • Channel
        • Java IO: Streams
          • Input streams
            • BufferedInputStream
            • DataInputStream
            • ObjectInputStream
            • FilterInputStream
            • ByteArrayInputStream
        • Java IO: Pipes
        • Java IO: Byte & Char Arrays
        • Java IO: Input Parsing
          • PushbackReader
          • StreamTokenizer
          • LineNumberReader
          • PushbackInputStream
        • System.in, System.out, System.error
        • Java IO: Files
          • FileReader
          • FileWriter
          • FileOutputStream
          • FileInputStream
      • Multithreading
        • Thread liveness
        • False sharing
        • Actor model
        • Singleton
        • Future, CompletableFuture
        • Semaphore
      • Coursera: parallel programming
      • Coursera: concurrent programming
      • Serialization
      • JVM internals
      • Features track
        • Java 8
      • Distributed programming
      • Network
      • Patterns
        • Command
      • Garbage Collectors
        • GC Types
        • How GC works
        • Tools for GC
    • Kotlin
      • Scope functions
      • Inline value classes
      • Coroutines
      • Effective Kotlin
    • Javascript
      • Javascript vs Java
      • TypeScript
    • SQL
      • select for update
    • Python
      • __init.py__
  • OS components
    • Network
      • TCP/IP model
        • IP address in action
      • OSI model
  • 🟢Specifications
    • JAX-RS
    • REST
      • Multi part
  • 🟢Protocols
    • HTTP
    • OAuth 2.0
    • LDAP
    • SAML
  • 🟢Testing
    • Selenium anatomy
    • Testcafe
  • 🟢Tools
    • JDBC
      • Connection pool
    • Gradle
    • vim
    • git
    • IntelliJ Idea
    • Elastic search
    • Docker
    • Terraform
    • CDK
    • Argo CD
      • app-of-app setup
    • OpenTelemetry
    • Prometheus
    • Kafka
      • Consumer lag
  • 🟢CI
    • CircleCi
  • 🟢Platforms
    • AWS
      • VPC
      • EC2
      • RDS
      • S3
      • IAM
      • CloudWatch
      • CloudTrail
      • ELB
      • SNS
      • Route 53
      • CloudFront
      • Athena
      • EKS
    • Kubernetes
      • Networking
      • RBAC
      • Architecture
      • Pod
        • Resources
      • How to try
      • Kubectl
      • Service
      • Tooling
        • ArgoCD
        • Helm
        • Istio
    • GraalVM
    • Node.js
    • Camunda
      • Service tasks
      • Transactions
      • Performance
      • How it executes
  • 🟢Frameworks
    • Hibernate
      • JPA vs Spring Data
    • Micronaut
    • Spring
      • Security
      • JDBC, JPA, Hibernate
      • Transactions
      • Servlet containers, clients
  • 🟢Awesome
    • Нейробиология
    • Backend
      • System design
    • DevOps
    • Data
    • AI
    • Frontend
    • Mobile
    • Testing
    • Mac
    • Books & courses
      • Path: Java Concurrency
    • Algorithms
      • Competitive programming
    • Processes
    • Finance
    • Electronics
  • 🟢Electronics
    • Arduino
    • IoT
  • Artificial intelligence
    • Artificial Intelligence (AI)
  • 🚀Performance
    • BE
  • 📘Computer science
    • Data structures
      • Array
      • String
      • LinkedList
      • Tree
    • Algorithms
      • HowTo algorithms for interview
  • 🕸️Web dev (Frontend)
    • Trends
    • Web (to change)
  • 📈Data science
    • Time series
Powered by GitBook
On this page
  • LineNumberReader Example
  • Line Numbers in Parsing
  • Closing a LineNumberReader

Was this helpful?

  1. Programming languages
  2. Java
  3. IO / NIO
  4. Java IO: Input Parsing

LineNumberReader

The Java LineNumberReader class (java.io.LineNumberReader is a BufferedReader that keeps track of line numbers of the read characters. Line numbering begins at 0. Whenever the LineNumberReader encounters a line terminator in the characters returned by the wrapped Reader, the line number is incremented.

You can get the current line number from the LineNumberReader by calling the getLineNumber() method. You can also set the current line number, should you need to, by calling the setLineNumber() method.

LineNumberReader Example

Here is a simple Java LineNumberReader example:

LineNumberReader lineNumberReader = 
    new LineNumberReader(new FileReader("c:\\data\\input.txt"));

int data = lineNumberReader.read();
while(data != -1){
    char dataChar = (char) data;
    data = lineNumberReader.read();
    int lineNumber = lineNumberReader.getLineNumber();
}
lineNumberReader.close();

This example first creates a LineNumberReader, and then shows how to read all the characters from it, and also shows how to get the line number (for each character read, in fact, which may be a bit more than you need).

Line Numbers in Parsing

Line number can be handy if you are parsing a text file that can contain errors. When reporting the error to the user, it is easier to correct the error if your error message includes the line number where the error was encountered.

Closing a LineNumberReader

When you are finished reading characters from the LineNumberReader you should remember to close it. Closing a LineNumberReader will also close the Reader instance from which the LineNumberReader is reading.

Closing a LineNumberReader is done by calling its close() method. Here is how closing a LineNumberReader looks:

lineNumberReader.close();
Reader reader = new FileReader("data/text.txt");

try(LineNumberReader lineNumberReader =
    new LineNumberReader(reader)){

    String line = lineNumberReader.readLine();
    while(line != null) {
        //do something with line

        line = lineNumberReader.readLine();
    }

}

Notice how there is no longer any explicit close() method call. The try-with-resources construct takes care of that.

Notice also that the first FileReader instance is not created inside the try-with-resources block. That means that the try-with-resources block will not automatically close this FileReader instance. However, when the LineNumberReader is closed it will also close the Reader instance it reads from, so the FileReader instance will get closed when the LineNumberReader is closed.

PreviousStreamTokenizerNextPushbackInputStream

Last updated 2 years ago

Was this helpful?

You can also use the construct introduced in Java 7. Here is how to use and close a LineNumberReader looks with the try-with-resources construct:

🟢
try-with-resources