April 4, 2024

How to Read Delimited File in Java

If you have to read delimited file in Java and parse it then you can do it using the following two ways-

  1. Using Scanner class with useDelimiter() method.
  2. Read file using BufferedReader line by line and then split each line using split() method.

1. Using Scanner class to read delimited file in Java

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches white space. The scanner can also use delimiters other than white space for that useDelimiter() method is used. Let’s see some examples of using Scanner class to read delimited file in Java.

Reading CSV file using Scanner in Java

Here is an example CSV file which denotes Account From, Account To and Amount Transferred.

1001,1003,2000
1006,2004,3000
1005,1007,10000

Which you want to read using Scanner class and parse it to display the fields.

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class ReadDelimited {
  public static void main(String[] args) {
    Scanner sc = null;
    try {
      sc = new Scanner(new File("D:\\acct.csv"));

      // Check if there is another line of input
      while(sc.hasNextLine()){
        String str = sc.nextLine();
        // parse each line using delimiter
        parseData(str);
      }
    } catch (IOException  exp) {
      // TODO Auto-generated catch block
      exp.printStackTrace();
    }finally{
      if(sc != null)
        sc.close();
    }	  		
  }
	
  private static void parseData(String str){	
    String acctFrom, acctTo, amount;
    Scanner lineScanner = new Scanner(str);
    lineScanner.useDelimiter(",");
    while(lineScanner.hasNext()){
      acctFrom = lineScanner.next();
      acctTo = lineScanner.next();
      amount = lineScanner.next();
      System.out.println("Account From- " + acctFrom + " Account To- " + acctTo + 
       " Amount- " + amount);  
    }
    lineScanner.close();
  }
}
Output
Account From- 1001 Account To- 1003 Amount- 2000
Account From- 1006 Account To- 2004 Amount- 3000
Account From- 1005 Account To- 1007 Amount- 10000

Reading pipe (|) delimited file in Java using Scanner

Here is another example Java program showing how you can read pipe delimited data using Scanner in Java.

1001|1003|2000
1006|2004|3000
1005|1007|10000

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class ReadDelimited {
  public static void main(String[] args) {
    Scanner sc = null;
    try {
      sc = new Scanner( new File("D:\\test.txt"));
      
      // Check if there is another line of input
      while(sc.hasNextLine()){
        String str = sc.nextLine();
        // parse each line using delimiter
        parseData(str);
      }
     
    } catch (IOException  exp) {
      // TODO Auto-generated catch block
      exp.printStackTrace();
    }finally{
      if(sc != null)
        sc.close();
    }	  		
  }
	
  private static void parseData(String str){	
    String acctFrom, acctTo, amount;
    Scanner lineScanner = new Scanner(str);
    lineScanner.useDelimiter("\\|");
    while(lineScanner.hasNext()){
      acctFrom = lineScanner.next();
      acctTo = lineScanner.next();
      amount = lineScanner.next();
      System.out.println("Account From- " + acctFrom + " Account To- " + acctTo + 
         " Amount- " + amount);  
    }
    lineScanner.close();
  }
}
Output
Account From- 1001 Account To- 1003 Amount- 2000
Account From- 1006 Account To- 2004 Amount- 3000
Account From- 1005 Account To- 1007 Amount- 10000

Since pipe symbol is a reserved character you do need to escape it, that is why lineScanner.useDelimiter("\\|"); is used.

2. Using split() method to split delimited data

Another way to read delimited file in Java is to read file line by line, you can use BufferedReader to read the file and then split delimited data using split method. If we take the same pipe delimited file as used above then the Java example is as follows.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadDelimited {
  public static void main(String[] args) {
    BufferedReader br = null;
    try{
      String strLine;
      //FileReader instance wrapped in a BufferedReader
      br = new BufferedReader(new FileReader("D:\\test.txt"));
       
      while((strLine = br.readLine()) != null){
        parseData(strLine);
      }
    }catch(IOException exp){
      System.out.println("Error while reading file " + exp.getMessage());
    }finally {
      try {
        // Close the stream
        if(br != null){
          br.close();
        }
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }  		
  }
	
  private static void parseData(String str){	
    String acctFrom, acctTo, amount;
    // parsing using split method
    String[] data = str.split("\\|");
    System.out.println("Account From- " + data[0] + " Account To- " + data[1] + 
         " Amount- " + data[2]);  
  }
}
Output
Account From- 1001 Account To- 1003 Amount- 2000
Account From- 1006 Account To- 2004 Amount- 3000
Account From- 1005 Account To- 1007 Amount- 10000

That's all for the topic How to Read Delimited File in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

April 3, 2024

How to Create And Start Thread in Java

In order to create a thread in Java you need to get an instance of java.lang.Thread class. You can do it in two ways.

  1. By implementing Runnable interface.
  2. By Extending Thread class.

Whichever of these two ways is chosen by you to create a thread in Java you need to override run() method and provide the code that will run in that thread. Thread’s run() method will be executed once you call start() method on the created thread.

Creating and starting thread in Java involves the following steps.

  1. Get an instance of the Thread class.
  2. Call start method on the created thread object- thread.start();
  3. Once the thread is started run method will be executed.

Creating thread by implementing Runnable interface

One of the ways to create a thread in Java is to implement the Runnable interface.

Runnable interface is a functional interface in Java with a single method run() which has to be implemented. That's how Runnable interface is defined in java.lang package.

@FunctionalInterface
public interface Runnable {
  public abstract void run();
}
Example code using Runnable
public class TestThread implements Runnable {
  @Override
  public void run() {
    System.out.println("Executing run method");
  }
}

At this stage you have a class of type Runnable (not yet of type Thread). Thread class has constructors where you can pass Runnable as a parameter, using one of those constructors you can get a thread instance.

Two of those constructors which are normally used to create a thread are as follows-

  • Thread(Runnable target)
  • Thread(Runnable target, String name)

You need to pass the Runnable instance to one of these constructors to create a thread. Following code shows how you can do it.

public class ThreadDemo {
  public static void main(String[] args) {
    // Passing an instance of type runnable 
    Thread thread = new Thread(new TestThread());
    thread.start();
  }
}

Running this code will instantiate a thread and start it. Ultimately the run() method will be executed by the thread.

Output
Executing run method

Creating thread by extending Thread class

Another way to create thread in Java is to subclass the Thread class and override the run method. Then you can create an instance of that class and call start() method.

public class TestThread extends Thread {
  @Override
  public void run() {
    System.out.println("Executing run method");
  }
  public static void main(String[] args) {
    TestThread thread = new TestThread();
    thread.start();
  }
}
Output
Executing run method

Which of these approach to choose

Since there are two ways to create thread in Java so the question arises which of these two approach should be used. The preferred way is to implement Runnable interface.

When you implement Runnable interface you still have a choice to extend another class as you are not extending Thread class. Note that in Java you can extend only one class.

Thread class has many other methods except run() method but mostly you will just override run() method and provide the code that has to be executed by the Thread. Same thing can be done by implementing Runnable interface. If you are not modifying or enhancing any other method of the Thread class then why extend it.

Using anonymous class to implement run() method

When creating thread in Java by extending Thread class or implementing Runnable interface, you can also use anonymous class to implement run method.

When extending Thread class

We can have an anonymous inner class that extends a class without actually extending that class. You can create an anonymous inner class and provide run method implementation there.

public class TestThread {
  public static void main(String[] args) {
    //  anonymous inner class
    Thread thread = new Thread(){
      @Override
      public void run() {
        System.out.println("Executing run method");
      }
    };
    thread.start();
  }
}
When implementing Runnable interface
public class TestThread {
  public static void main(String[] args) {
    new Thread(new Runnable() {
      @Override
      public void run() {
        System.out.println("Executing run method");
      }
    }).start();
  }
}
Implementing Runnable as a lambda expression

Since Runnable is a functional interface it can also be implemented as a lambda expression Java 8 onward.

public class TestThread {
  public static void main(String[] args) {
    Runnable r = () -> {System.out.println("Executing run method");};
    // passing runnable instance
    new Thread(r).start();
  }
}

That's all for the topic How to Create And Start Thread in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

April 2, 2024

Main Thread in Java

Java is one of the first programming language to provide built-in support for multi-threading. In fact when a Java program starts one thread starts running immediately that thread is known as main thread in Java.

If you ever tried to run a Java program with compilation errors you would have seen the mentioning of main thread. Here is a simple Java program that tries to call the non-existent getValue() method.

public class TestThread {	
  public static void main(String[] args) {
    TestThread t = new TestThread();
    t.getValue();
  }
}
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
  The method getValue() is undefined for the type TestThread

As you can see in the error when the program is executed, main thread starts running and that has encountered a compilation problem.

Java Main Thread

Main thread in Java is important as your Java program will start running on this thread. Additional threads spawned in your program will inherit some of the properties from the main thread like thread priority, creating threads as non-daemon threads as main thread is a non-daemon thread.

By default name of the main thread is "main" and the thread priority of main thread is 5. This main thread belongs to a thread group called main.

The Java Virtual Machine continues to execute threads until all threads that are not daemon threads have died. If you have spawned other threads in your program that are non-daemon then main thread may terminate before those threads. Let’s see a Java example to clarify these statements.

Main thread Java example

In the program we’ll display the name of the thread in the main method and using isAlive() method it is also verified whether thread is still alive or terminated.

Three more threads are also spawned, in order to keep checking on the status of the main thread its reference is sent to the class that implements Runnable.

class NumThread implements Runnable{
  Thread thread;
  public NumThread(Thread thread) {
    this.thread = thread;
  }
  @Override
  public void run() {
    for (int i = 0; i < 5; i++) {
      System.out.println(Thread.currentThread().getName() + " : " + i);
    } 
    System.out.println("Thread name " + thread.getName());
    System.out.println("Main Thread Status " + thread.isAlive());
  }
}

public class ThreadPriority {
  public static void main(String[] args) {
    // Information about main thread
    System.out.println("Thread name- " + Thread.currentThread().getName());
    System.out.println("Priority of " + Thread.currentThread().getName() + " thread is " + Thread.currentThread().getPriority());
    System.out.println("Group " + Thread.currentThread().getName() + " thread belongs to- " + Thread.currentThread().getThreadGroup());
    // Creating threads
    Thread t1 = new Thread(new NumThread(Thread.currentThread()), "Thread-1");
    Thread t2 = new Thread(new NumThread(Thread.currentThread()), "Thread-2");
    Thread t3 = new Thread(new NumThread(Thread.currentThread()), "Thread-3");
    t1.start();
    t2.start(); 
    t3.start();
    System.out.println("Thread name " + Thread.currentThread().getName());
    System.out.println("Thread name " + Thread.currentThread().isAlive());
  }
}
Output
Thread name- main
Priority of main thread is 5
Group main thread belongs to- java.lang.ThreadGroup[name=main,maxpri=10]
Thread name main
Thread name true
Thread-1 : 0
Thread-1 : 1
Thread-1 : 2
Thread-1 : 3
Thread-1 : 4
Thread name main
Main Thread Status false
Thread-3 : 0
Thread-3 : 1
Thread-3 : 2
Thread-3 : 3
Thread-3 : 4
Thread name main
Main Thread Status false
Thread-2 : 0
Thread-2 : 1
Thread-2 : 2
Thread-2 : 3
Thread-2 : 4
Thread name main
Main Thread Status false

As you can see from the output priority of the main thread is 5 and the thread group is also main. main You can also verify that the main thread is terminated while other threads are still executing.

That's all for the topic Main Thread in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

April 1, 2024

Thread Group in Java

All threads belong to one of a thread group in Java. When you create a thread in Java it is put into a thread group specified either by you or to the same group as the thread that created it if no thread group is explicitly specified.

Default thread group

When a Java application is started one thread starts running immediately which is known as main thread in Java and this main thread belongs to a thread group called main. If you create other threads (with in the context of main thread) with out specifying thread group then these thread will also belong to main thread group.

Usage of thread group in Java

Thread groups provide a convenient way to manage multiple threads as a single thread group object. Using that thread group object you can manipulate all the threads belonging to that group as a single unit rather than doing that individually. For example-

Thread.currentThread().getThreadGroup().interrupt();

This will interrupt all the thread belonging to that thread group with a single statement.

ThreadGroup Class in Java

Java provides a class java.lang.ThreadGroup for creating thread groups in Java.

ThreadGroup Class Constructors

ThreadGroup class has two constructors for creating thread groups.

  • public ThreadGroup(String name)- Constructs a new thread group. The parent of this new group is the thread group of the currently running thread.
  • public ThreadGroup(ThreadGroup parent, String name)- Creates a new thread group. The parent of this new group is the specified thread group.
Methods in ThreadGroup Class

Some of the important methods of the ThreadGroup Class are.

  • String getName()- Returns the name of this thread group.
  • ThreadGroup getParent()- Returns the parent of this thread group.
  • boolean isDaemon()- Tests if this thread group is a daemon thread group.
  • void checkAccess()- Determines if the currently running thread has permission to modify this thread group.
  • int activeCount()- Returns an estimate of the number of active threads in this thread group and its subgroups. Recursively iterates over all subgroups in this thread group.
  • int enumerate(Thread[] list)- Copies into the specified array every active thread in this thread group and its subgroups.
  • void interrupt()- Interrupts all threads in this thread group.
  • void list()- Prints information about this thread group to the standard output.

Creating Thread in specific thread group

Thread class in Java provides constructor where you can specify a thread group. Few of those constructors are listed here.

  • public Thread(ThreadGroup group, Runnable target)
  • public Thread(ThreadGroup group, String name)
  • public Thread(ThreadGroup group, Runnable target, String name)

Thread group Java example

public class TGDemo implements Runnable {
  public static void main(String[] args) {
    System.out.println("In main method " + Thread.currentThread().getName() 
        + " Group " + Thread.currentThread().getThreadGroup().getName());
    TGDemo runnableTarget = new TGDemo();
    // Creating two thread groups
    ThreadGroup group1 = new ThreadGroup("Group-1");
    ThreadGroup group2 = new ThreadGroup("Group-2");
    // Creating 4 threads belonging to the created thread groups
    Thread t1 = new Thread(group1, runnableTarget, "T1");
    Thread t2 = new Thread(group1, runnableTarget, "T2");
    Thread t3 = new Thread(group2, runnableTarget, "T3");
    Thread t4 = new Thread(group2, runnableTarget, "T4");
    t1.start();
    t2.start();
    t3.start();
    t4.start();
    group1.list();
    group2.list();
  }

  @Override
  public void run() {
    System.out.println("In run method " + Thread.currentThread().getName() 
        + " Group " + Thread.currentThread().getThreadGroup().getName());
    if(Thread.currentThread().getThreadGroup().getName().equals("Group-1")){
      Thread.currentThread().getThreadGroup().interrupt();
    }
    if (Thread.interrupted()) {
      System.out.println("interrupted " + Thread.currentThread().getName());
    }
  }
}
Output
In main method main Group main
In run method T1 Group Group-1
java.lang.ThreadGroup[name=Group-1,maxpri=10]
In run method T2 Group Group-1
Thread[T1,5,Group-1]
In run method T4 Group Group-2
Thread[T2,5,Group-1]
java.lang.ThreadGroup[name=Group-2,maxpri=10]
Thread[T3,5,Group-2]
interrupted T1
interrupted T2
In run method T3 Group Group-2

As you can see initially when the application starts main thread starts running and it belongs to thread group main.

Then two thread groups "Group-1" and "Group-2" are created. Four thread are also created to of these threads belong to “Group-1” and other two belongs to “Group-2”.

In run() method you can see specific logic is there for threads belonging to "Group-1".

Reference- https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/ThreadGroup.html

That's all for the topic Thread Group in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like