Wednesday, April 21, 2021

How ArrayList Works Internally in Java

ArrayList arguably would be the most used collection along with the HashMap. Many of us programmers whip up code everyday which contains atleast one of these data structures to hold objects. I have already discussed how HashMap works internally in Java, in this post I'll try to explain how ArrayList internally works in Java.

As most of us would already be knowing that ArrayList is a Resizable-array implementation of the List interface i.e. ArrayList grows dynamically as the elements are added to it. So let's try to get clear idea about the following points-

  • How ArrayList is internally implemented in Java.
  • What is the backing data structure for an ArrayList.
  • How it grows dynamically and ensures that there is always room to add elements.
Because of all these side questions it is also a very important Java Collections interview question.

Note - Code of ArrayList used here for reference is from Java 10.


Where does ArrayList internally store elements

Basic data structure used by Java ArrayList to store objects is an array of Object class, which is defined as follows-

transient Object[] elementData;

I am sure many of you would be thinking why transient and how about serializing an ArrayList then?
ArrayList provides its own version of readObject and writeObject methods so no problem in serializing an ArrayList and that is the reason, I think, of making this Object array as transient.

Tuesday, April 20, 2021

EnumSet in Java With Examples

EnumSet in Java is a specialized set implementation for use with enum types. EnumSet was introduced in Java 5 along with the Enum. All of the elements stored in an EnumSet must, explicitly or implicitly, come from a single enum type that is specified while creating the set. All basic operations of the EnumSet execute in constant time. They are likely (though not guaranteed) to be much faster than their HashSet counterparts.

According to Java docs "Enum sets are represented internally as bit vectors. This representation is extremely compact and efficient. The space and time performance of this class should be good enough to allow its use as a high-quality, typesafe alternative to traditional int-based "bit flags." Even bulk operations (such as containsAll and retainAll) should run very quickly if their argument is also an enum set."

How EnumSet works in Java

One of the things to note about EnumSet is that it is an abstract class and uses factory methods to create objects. There are two concrete implementations of EnumSet in Java-

  • RegularEnumSet- Private implementation class for EnumSet, for "regular sized" enum types
  • JumboEnumSet- Private implementation class for EnumSet, for "jumbo" enum types (i.e., those with more than 64 elements).
Both of these classes can't be instantiated directly by the user as these classes have default (package-private) access.

Depending upon the size of the Enum any of these classes is instantiated by the EnumSet class itself. If Enum has 64 or fewer enum constants then RegularEnumSet is used otherwise JumboEnumSet.

Monday, April 19, 2021

Converting String to float in Java

There are several instances when you want to convert a String to float data type so in this post we’ll see what different ways do we have to convert String to float in Java.

In Java, Float class provides two methods for converting string to float-

  • parseFloat(String s)- Returns a new float initialized to the value represented by the specified String. Throws NumberFormatException if the string does not contain a parsable number. See example.
  • valueOf(String s)- Returns a Float object holding the float value represented by the String argument s. Throws NumberFormatException if the String does not contain a parsable number. See example.

Here Few things to note are-

  1. Both of the methods are static so you can use them directly with the class i.e. Float.parseFloat(String s) and Float.valueOf(String s).
  2. If you have noticed parseFloat method returns float (primitive data type) where as valueOf() method returns Float class object.
  3. String passed should have digits only except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value.
  4. You can use “f” or “F” (even d or D which denotes double) with the float value so having string as “56.78f” will not throw NumberFormatException while converting where as “56.78a” will throw exception.

Float class also has a constructor that takes String as argument so that is also one way to convert string to float. Note that this constructor is deprecated Java 9 onward.

  • Float(String s)- Constructs a newly allocated Float object that represents the floating-point value of type float represented by the string.

Sunday, April 18, 2021

Converting String to double in Java

There are several instances when you want to convert a string to double data type so in this post we’ll see what different ways do we have to convert String to double in Java.

Double class in Java provides two methods for converting String to double-

  • parseDouble(String s)- Returns a new double initialized to the value represented by the specified String. Throws NumberFormatException if the string does not contain a parsable double.
  • valueOf(String s)- Returns a Double object holding the double value represented by the argument string s. Throws NumberFormatException if the string does not contain a parsable number. If s is null, then a NullPointerException is thrown.

Here Few things to note are-

  1. Both of the methods are static so you can use them directly with the class i.e. Double.parseDouble(String s) and Double.valueOf(String s).
  2. If you have noticed parseDouble method returns double (primitive data type) where as valueOf() method returns Double class object.
  3. String passed should have digits only except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value.
  4. You can use “d” or “D” (even f or F which denotes float) with the value so having string as “43.67d” will not throw NumberFormatException while converting where as “43.67e” will throw exception.

Note that Double class also has a constructor that takes String as argument so that is also one way to convert string to float.

Double(String s)- Constructs a newly allocated Double object that represents the floating-point value of type double represented by the string.

Wednesday, April 14, 2021

How to Read Properties File in Java

In this tutorial you will see how to read a properties file in Java. If you have any configurable data in your application like DB configuration, user settings its better to keep it in a properties file and read it from there. A properties file stores data in the form of key/value pair.

For reading a properties file in Java there are two ways to load properties file-

  1. Loading properties file from the file system. See example.
  2. Loading properties file from classpath. See example.

Project structure

For this example we’ll have a properties file named app.properties file in a folder called resource. The resource folder is at the same level at the src folder in the Java project.

read properties file in java

Steps for reading a properties file in Java

  1. Create an instance of Properties class.
  2. Create a FileInputStream by opening a connection to the properties file.
  3. Read property list (key and element pairs) from the input stream using load() method of the Properties class.

Content of the properties file

Here the properties file used is named app.properties file with it’s content as-

user=TestUser
url=https://www.netjstech.com

Loading properties file from the file system

One way to read properties file in Java is to load it from the file system.

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PropDemo {
  private Properties properties = new Properties();
  public static void main(String[] args) {
    PropDemo pDemo = new PropDemo();
    pDemo.loadPropertiesFile();
    pDemo.readProperties();
  }
  
  // This method is used to load the properties file
  private void loadPropertiesFile(){
    InputStream iStream = null;
      try {
        // Loading properties file from the path (relative path given here)
        iStream = new FileInputStream("resource/app.properties");   
        properties.load(iStream);
      } catch (IOException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      }finally {
        try {
          if(iStream != null){
            iStream.close();
          }
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }
  
  /**
  * Method to read the properties from a
  * loaded property file
  */
  private void readProperties(){
    System.out.println("User name - " + properties.getProperty("user"));
    System.out.println("URL - " + properties.getProperty("url"));
    // reading property which is not there
    System.out.println("City - " + properties.getProperty("city"));
  }
}

Output

User name - TestUser
URL - https://www.netjstech.com
City - null

Here you can see that in the code there is an attempt to read the property “city” which doesn’t exist in the app.properties file that’s why it is retrieved as null.

Loading properties file from classpath

If you have properties file in the project classpath then you can load it by using the getResourceAsStream method. That is another way to read properties file in Java.

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PropDemo {
 private Properties properties = new Properties();
 public static void main(String[] args) {
   PropDemo pDemo = new PropDemo();
   pDemo.loadProperties();
   pDemo.readProperties();
 }
 
 // This method is used to load the properties file
 private void loadProperties(){
   InputStream iStream = null;
   try {
    // Loading properties file from the classpath
    iStream = this.getClass().getClassLoader()
                             .getResourceAsStream("app.properties");
    if(iStream == null){
     throw new IOException("File not found");
    }
    properties.load(iStream);
   } catch (IOException e) {
    e.printStackTrace();
   }finally {
    try {
     if(iStream != null){
      iStream.close();
     }
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
 }
  
 /**
  * Method to read the properties from a
  * loaded property file
 */
 private void readProperties(){
   System.out.println("User name - " + properties.getProperty("user"));
   System.out.println("URL - " + properties.getProperty("url"));
 }
}

Output

User name - TestUser
URL - https://www.netjstech.com

That's all for this topic How to Read Properties File in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. How to Read File From The Last Line in Java
  2. Unzip File in Java
  3. Reading File in Java Using Files.lines And Files.newBufferedReader
  4. Write to a File in Java
  5. How to Read Properties File in Spring Framework

You may also like-

  1. How to Create PDF From XML Using Apache FOP
  2. Setting And Getting Thread Name And Thread ID in Java
  3. How to Convert Date And Time Between Different Time-Zones in Java
  4. How to Reverse a String in Java
  5. Fail-Fast Vs Fail-Safe Iterator in Java
  6. Java ReentrantReadWriteLock With Examples
  7. BigDecimal in Java With Examples
  8. instanceof Operator in Java With Examples

Monday, April 12, 2021

Angular @Output() Decorator With Examples

Angular @Output() decorator in a child component or directive allows data to flow from the child to the parent. A property decorated with @Output in child component is used to raise an event to notify the parent of the change. That property must be of type EventEmitter, which is a class in @angular/core that you use to emit custom events.

Angular @Output() Decorator

@Output, $event and EventEmitter in Angular

In order to know how to use @Output decorator in Angular you should have idea about the following entities-

  • @Output decorator
  • EventEmitter class
  • $event object

1. @Output decorator

A property in a Component that emits a custom event is decorated with @Output decorator. For example in the statement

 @Output() messageEvent = new EventEmitter<string>();

messageEvent property is decorated with @Output() which means this property is going to emit a custom event. That is why this property is of type EventEmitter.

Sunday, April 11, 2021

Angular @Component Decorator With Examples

Decorators or annotations are used to provide metadata about the entity where these decorators are added. Angular @Component decorator provides metadata about the class and tells Angular that the decorated class is a Component class.

Angular @Component provides configuration metadata that determines how the component should be processed, instantiated, and used at runtime.

For example-

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
 ...
 ...

As you can see selector property here specifies value as ‘app-root’ which means any <app-root></app-root> tags that are used within a template will be compiled using the AppComponent class and get the functionality as defined in the class.

templateUrl is specified as ./app.component.html which means view template is loaded from the file app.component.html in the current directory.

Using styleUrls you can specify One or more relative paths or absolute URLs for files containing CSS stylesheets to use in this component. Here ./app.component.css is specified as css file which means styling for the component is done using hello-world.component.css in the current directory. By specifying style fields like this you can associate a specific css file to a component.

Saturday, April 10, 2021

ConcurrentLinkedQueue in Java With Examples

ConcurrentLinkedQueue in Java implements Queue interface and it was added in Java 5 along with other concurrent utilities like CyclicBarrier, CountDownLatch, Semaphore, ConcurrentHashMap etc.

ConcurrentLinkedQueue in Java is an unbounded thread-safe queue which stores its elements as linked nodes. This queue orders elements FIFO (first-in-first-out). The head of the queue is the element that has been on the queue the longest time. The tail of the queue is the element that has been on the queue the shortest time. New elements are inserted at the tail of the queue, and the queue retrieval operations obtain elements at the head of the queue.

Like most other concurrent collection implementations, ConcurrentLinkedQueue class does not permit the use of null elements.

Usage of ConcurrentLinkedQueue in Java

A ConcurrentLinkedQueue is an appropriate choice when many threads will share access to a common collection. Note that it doesn't block operations as it is done in the implementations of BlockingQueue interface like ArrayBlockingQueue, LinkedBlockingQueue. So there are no put() or take() methods which will wait if required.

Java ConcurrentLinkedQueue constructors

  • ConcurrentLinkedQueue()- Creates a ConcurrentLinkedQueue that is initially empty.
  • ConcurrentLinkedQueue​(Collection<? extends E> c)- Creates a ConcurrentLinkedQueue initially containing the elements of the given collection, added in traversal order of the collection's iterator.

Friday, April 9, 2021

Java SynchronousQueue With Examples

SynchronousQueue which is an implementation of the BlockingQueue interface was added in Java 5 along with other concurrent utilities like ConcurrentHashMap, ReentrantLock, Phaser, CyclicBarrier etc.

How SynchronousQueue differs from other implementations of BlockingQueue like ArrayBlockingQueue and LinkedBlockingQueue is that SynchronousQueue in Java does not have any internal capacity, not even a capacity of one. In SynchronousQueue each insert operation must wait for a corresponding remove operation by another thread, and vice versa.

What that means is, if you put an element in SynchronousQueue using put() method it will wait for another thread to receive it, you can't put any other element in the SynchronousQueue as it is blocked. Same way in case there is thread to remove an element (using take() method) but there is no element in the queue it will block and wait for an element in the queue.

Java SynchronousQueue differs in functionality

Since SynchronousQueue has a very special functionality which differs from other BlockingQueue implementations so methods in Java SynchronusQueue behave a little differently. Actually calling it a Queue itself is a bit of wrong statement as there is never more than one element present. It's more of a point-to-point handoff.

As an example take peek() method, which in other BlockingQueue implementations work as follows-

peek() - Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.

Since in SynchronousQueue an element is only present when you try to remove it so peek() method in this class always returns null.

Iterator in SynchronousQueue returns an empty iterator in which hasNext always returns false.

For purposes of other Collection methods a SynchronousQueue acts as an empty collection, so methods like

  • contains- Always returns false. A SynchronousQueue has no internal capacity.
  • remove- Always returns false. A SynchronousQueue has no internal capacity.
  • isEmpty()- Always returns true. A SynchronousQueue has no internal capacity.

Thursday, April 8, 2021

Lock Striping in Java Concurrency

If you have only one lock for the whole data structure like Array or Map and you are synchronizing it and using it in a multi-threaded environment, then effectively any given time only one thread can manipulate the map, as there is only a single lock. All the other threads would be waiting to get the monitor.

If you have to visualize a HashTable or a synchronized HashMap it can be depicted like the following image.

If there are 6 threads only one can get the lock and enter the synchronized collection. Even if the keys these threads want to get (or manipulate the values) are in different buckets as in the image if two threads want to access keys in bucket 0, two threads want to access keys in bucket 1 and two threads want to access keys in bucket n-3, any given time only one thread will get access.

Single lock for whole collection
Single lock for the whole collection

Wednesday, April 7, 2021

Angular HttpClient + Spring Boot REST API CRUD Backend Service

In this tutorial we’ll see how to communicate with a back end service using the Angular HttpClient. As an example we’ll take a Spring Boot REST API crud application as a back end service and connect to it from an Angular front end application using the Angular HttpClient.

In this post stress is more on explaining how to use Angular client HTTP API, how to make a request to back end service and how to catch errors.

Back end Spring Boot service

In the Spring Boot application we have a Rest Controller class with handler mappings for different CRUD operations. DB used is MySQL and the DB table is User.

To get more details and code for the Spring Boot CRUD application, refer this post- Spring Boot REST API CRUD Example With Spring Data JPA

Only change that is required in the Spring boot application is to add @CrossOrigin annotation in the Controller class to enable cross-origin resource sharing (CORS). If you won't use this annotation cross browser HTTP request won't be allowed and the Spring Boot application won't accept any request coming from http://localhost:4200

Tuesday, April 6, 2021

Print Odd-Even Numbers Using Threads And wait-notify Java Program

In this post we'll see a Java program to print odd and even numbers sequentially using two threads. One thread generates odd numbers and another even numbers. This Java program makes use of inter-thread communication using wait, notify, notifyAll to print odd-even numbers.

Java program to print odd-even numbers using threads

There is a class SharedPrinter whose object is shared between two threads. In this class there is a method printEvenNum() for printing even numbers and method printOddNum() for printing odd numbers.

These two methods are called by the respective threads EvenNumProducer and OddNumProducer and these threads communicate using wait and notify, of course from inside a synchronized block.

public class EvenOddThreadDemo {
  public static void main(String[] args) {
    // shared class object
    SharedPrinter sp = new SharedPrinter();
    // creating two threads
    Thread t1 = new Thread(new EvenNumProducer(sp, 10));
    Thread t2 = new Thread(new OddNumProducer(sp, 10));
    // starting threads
    t1.start();
    t2.start();
  }
}
// Shared class used by both threads
class SharedPrinter{
  boolean evenFlag = false;
 
  //Method for printing even numbers
  public void printEvenNum(int num){
    synchronized (this) {
      // While condition as mandated to avoid spurious wakeup
      while(!evenFlag){
        try {
          //asking current thread to give up lock
          wait();
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
      System.out.println(num);
      evenFlag = false;
      // Wake up thread waiting on this monitor(lock)
      notify();
    }
  }
 
  //Method for printing odd numbers
  public void printOddNum(int num){
    synchronized (this) {
      // While condition as mandated to avoid spurious wakeup
      while(evenFlag){
        try {
         //asking current thread to give up lock
         wait();
        } catch (InterruptedException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
        }
      }
      System.out.println(num);
      evenFlag = true;
      // Wake up thread waiting on this monitor(lock)
      notify();   
    }
  }
}

// Thread Class generating Even numbers
class EvenNumProducer implements Runnable{
  SharedPrinter sp;
  int index;
  EvenNumProducer(SharedPrinter sp, int index){
    this.sp = sp;
    this.index = index;
  }
  @Override
  public void run() {
    for(int i = 2; i <= index; i = i+2){
      sp.printEvenNum(i);
    }   
  }   
}

//Thread Class generating Odd numbers
class OddNumProducer implements Runnable{
  SharedPrinter sp;
  int index;
  OddNumProducer(SharedPrinter sp, int index){
    this.sp = sp;
    this.index = index;
  }
  @Override
  public void run() {
    for(int i = 1; i <= index; i = i+2){
      sp.printOddNum(i);
    }
  }
}

Output

1
2
3
4
5
6
7
8
9
10

That's all for this topic Print Odd-Even Numbers Using Threads And wait-notify Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Why wait(), notify() And notifyAll() Methods Are in Object Class And Not in Thread Class
  2. Why wait(), notify() And notifyAll() Must be Called Inside a Synchronized Method or Block
  3. How to Run Threads in Sequence in Java
  4. How to Create Deadlock in Java
  5. Producer-Consumer Java Program Using volatile

You may also like-

  1. Java Program to Create Your Own BlockingQueue
  2. Java Program to Get All DB Schemas
  3. Count Number of Words in a String Java Program
  4. How to Convert Date And Time Between Different Time-Zones in Java
  5. Marker interface in Java
  6. Synchronization in Java - Synchronized Method And Block
  7. Method Reference in Java
  8. Spring Java Configuration Example Using @Configurations

Monday, April 5, 2021

Print Odd-Even Numbers Using Threads And Semaphore Java Program

This Java program prints odd and even numbers alternatively using two threads. One thread prints odd numbers and another thread even numbers. This program makes use of inter-thread communication using Semaphore class which is present in concurrent util package.

The Semaphore class present in java.util.concurrent package is a counting semaphore in which a semaphore, conceptually, maintains a set of permits. Semaphore class has two methods that make use of permits-

  • acquire()- Acquires a permit from this semaphore, blocking until one is available, or the thread is interrupted. It has another overloaded version acquire(int permits).
  • release()- Releases a permit, returning it to the semaphore. It has another overloaded method release(int permits).

Java Program to print odd-even numbers using threads and semaphore

In the Java program there is class SharedPrinter whose object is shared between two threads. In this class there is a method printEvenNum() for printing even numbers and method printOddNum() for printing odd numbers.

These two methods are called by the respective threads EvenNumProducer and OddNumProducer and these threads communicate using semaphore. Idea is to have 2 semaphores when first is acquired release second, when second is acquired release first. That way shared resource has controlled access and there is inter-thread communication between the threads.

Note that one of the semaphore semEven is initialized with 0 permits that will make sure that even number generating thread doesn't start first.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class EvenOddSem {

 public static void main(String[] args) {
    SharedPrinter sp = new SharedPrinter();
    // Starting two threads
    ExecutorService executor = Executors.newFixedThreadPool(2);
    executor.execute(new EvenNumProducer(sp, 10));
    executor.execute(new OddNumProducer(sp, 10));
    executor.shutdown();
 }
}

//Shared class used by both threads
class SharedPrinter{
 boolean evenFlag = false;
 // 2 semaphores 
 Semaphore semEven = new Semaphore(0);
 Semaphore semOdd = new Semaphore(1);
 
 //Method for printing even numbers
 public void printEvenNum(int num){
  try {
   semEven.acquire();
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  System.out.println(num);
  semOdd.release(); 
 }
 
 //Method for printing odd numbers
 public void printOddNum(int num){
  try {
   semOdd.acquire();
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  System.out.println(num);
  semEven.release();
   
 }
}

//Thread Class generating Even numbers
class EvenNumProducer implements Runnable{
  SharedPrinter sp;
  int index;
  EvenNumProducer(SharedPrinter sp, int index){
    this.sp = sp;
    this.index = index;
  }
  @Override
  public void run() {
    for(int i = 2; i <= index; i = i+2){
      sp.printEvenNum(i);
    }   
  }  
}

//Thread Class generating Odd numbers
class OddNumProducer implements Runnable{
  SharedPrinter sp;
  int index;
  OddNumProducer(SharedPrinter sp, int index){
    this.sp = sp;
    this.index = index;
  }
  @Override
  public void run() {
    for(int i = 1; i <= index; i = i+2){
      sp.printOddNum(i);
    }
  }
} 

Output

1
2
3
4
5
6
7
8
9
10

That's all for this topic Print Odd-Even Numbers Using Threads And Semaphore Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. How to Run Threads in Sequence in Java
  2. How to Create Deadlock in Java
  3. Setting And Getting Thread Name And Thread ID in Java
  4. Java Program to Create Your Own BlockingQueue
  5. Java Multithreading Interview Questions And Answers

You may also like-

  1. Convert float to String in Java
  2. How to Read Input From Console in Java
  3. Synchronization in Java - Synchronized Method And Block
  4. Race Condition in Java Multi-Threading
  5. Java ReentrantLock With Examples
  6. Lambda Expressions in Java 8
  7. How to Inject Prototype Scoped Bean into a Singleton Bean in Spring
  8. Autowiring in Spring Using @Autowired and @Inject Annotations

Saturday, April 3, 2021

Difference Between Comparable and Comparator in Java

While sorting elements in collection classes, these two interfaces Comparable and Comparator in Java come into picture. Both of these interfaces are used to sort collection elements. An obvious question which comes to mind is why two different interfaces?

In this post we'll see the difference between Comparable and Comparator interfaces in Java and why both of them are required. Before going into the differences between these two, let's have a brief introduction of both.


Comparable interface in Java

Comparable interface is defined as follows-

public interface Comparable<T> {
 public int compareTo(T o);
}

Classes implementing this interface need to provide sorting logic in compareTo() method.

The ordering imposed by the implementation of this interface is referred to as the class' natural ordering, and the implemented compareTo method is referred to as its natural comparison method.
Classes implementing this interface can be sorted automatically by Collections.sort (and Arrays.sort) method. Objects that implement this interface can be used as keys in a sorted map (like TreeMap) or as elements in a sorted set (like TreeSet) without the need to specify a comparator.

Friday, April 2, 2021

try-catch Block in Java Exception Handling

In this post we'll see how exception handling can be done using try-catch block in Java.

try block in Java

try block is used to enclose the code that might throw an exception. try block must be followed by either catch or finally block or both.

General form of Java try block

try {
  code 
}
catch and/or finally blocks
 

catch Block in Java

catch block is used to handle the exception thrown with in a try block. There can't be any code between the end of the try block and the beginning of the first catch block.

Thursday, April 1, 2021

How to Read File From The Last Line in Java

There are applications where you have to read huge files line by line may be using some tool like Pentaho, Camel. Let's say these files are in the format header, records and footer and you need to check something in the footer (last line of the file) and if that condition is not met you need to reject the file. Now, reading line by line in such scenario, will be wasteful as you'll anyway reject the file in the end.

So for such scenarios it is better to read the last line (or may be last N lines) of the file, to have better throughput. In this post you will see how to read a file from the last line in Java.


In Java reading file from the end can be done using RandomAccessFile which has a seek method to set the file-pointer offset, measured from the beginning of the file.

Apache Commons IO also has a ReversedLinesFileReader class which reads lines in a file reversely.

File used

Let's say you have a file aa.txt which has the following content-

This is the first line.
This is the second line.
This is the third line.
This is the fourth line.

And you want to read last line of this file using Java.