dcsimg
LinkedIn
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
May 18, 2021

Working with Multiple Delimiters in Java

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
MS Sridhar
 
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date