How do I split a string using Scanner class?

Category: java.util, viewed: 10427 time(s).

Instead of using the StringTokenizer class or the String.split() method we can use the java.util.Scanner class to split a string.

package org.kodejava.example.util;

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

public class ScannerTokenDemo {
    public static void main(String[] args) {
        //
        // This file contains some data as follow:
        // a, b, c, d
        // e, f, g, h
        // i, j, k, l
        //
        File file = new File("data.txt");
        try {
            //
            // Here we use the Scanner class to read file content line-by-line.
            //
            Scanner scanner = new Scanner(file);
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                
                //
                // From the above line of code we got a line from the file
                // content. Now we want to split the line with comma as the 
                // charater delimiter.
                //
                Scanner lineScanner = new Scanner(line);
                lineScanner.useDelimiter(",");
                while (lineScanner.hasNext()) {
                    //
                    // Get each splited data from the Scanner object and print
                    // the value.
                    //
                    String part = lineScanner.next();
                    System.out.print(part + ", ");
                }                
                System.out.println();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}
Click here to lend your support to: Kode Java Org and make a donation at www.pledgie.com !

 

Can't find what you are looking for? Join our FORUMS and ask some questions!
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Sponsored Links

Our Friends

Statistics

Locations of visitors to this page
visitor stats