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.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 follows:
// 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
// character delimiter.
Scanner lineScanner = new Scanner(line);
lineScanner.useDelimiter(",");
while (lineScanner.hasNext()) {
// Get each split 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();
}
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024