dcsimg
 

Working with Multiple Delimiters in Java

Tuesday May 18th 2021 by MS Sridhar
Article Image

How to work with multiple delimiters in a file with Java. Code along with our example.

In Java, you sometimes have to use delimiters - such as a period or hyphen - to separate data fields. This Java tutorial shows you how to work with files containing more than one delimiter.

*/

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

public class MultiDelimiter {

    public static void main(String[] args)
	{
		MultiDelimiter multiDelimiter = new MultiDelimiter();
		multiDelimiter.proceed();
	}

	private void proceed()
	{
        String fileName = "MultiDelimiter.csv";
		File file;
		Scanner scanner = null;
		
        try{
			file = new File(fileName);
			scanner = new Scanner(file);
		}catch(FileNotFoundException fnfe)
		{
			System.out.println("Exception: " + fnfe);
		}

        while (scanner.hasNext())
        {
            String line = scanner.nextLine();
            String[] tokens = line.split("[,:]");
            
            System.out.println("Name: " + tokens[0] + ", Age: " + tokens[1] + ", YearOfPassingMasters: " + tokens[2]);
        }
        
        scanner.close();
	}
}

/*

Output:

$java MultiDelimiter
Name: Joe White, Age: 35, YearOfPassingMasters: 2000
Name: Kyte May, Age: 34, YearOfPassingMasters: 1989
Name: Lynn Kat, Age: 36, YearOfPassingMasters: 1996
Home
Mobile Site | Full Site