In this program, we will take a look at how to read a file and split its contents using StringTokenizer Class in Java,
File Content:Id, Name, Age, Gender
1, Sam, 22, Male
2, Rita, 32, Female
3, Alex, 21, Female
4, Kate, 22, Female
Program:
import java.io.*;
import java.util.StringTokenizer;
/**
* Read a file and split lines
* using StringTokenizer
*/
public class StringTokenizerExample {
public static void main(String[] args) throws IOException {
File csvFile = new File("/Users/c2c/input-file.csv");
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
String line;
while ((line = br.readLine()) != null) {
StringTokenizer stringTokenizer = new StringTokenizer(line,",");
while (stringTokenizer.hasMoreTokens()) {
//Split the line using stringTokenizer
System.out.println(stringTokenizer.nextToken().trim());
}
}
}
}
}
Output:
Id
Name
Age
Gender
1
Sam
22
Male
2
Rita
32
Female
3
Alex
21
Female
4
Kate
22
Female
More Posts related to Java,
- Deep Dive into Java 8 Predicate Interface
- Read and Parse XML file using Java DOM Parser [Java Tutorial]
- Java 8 Predicate Functional Interface isEqual() Method Example
- Convert Multidimensional Array toString In Java
- How to read int value using Scanner Class Java
- Spring Boot AI + LLM + Java Code Example
- Write to a File using Java Stream API
- Implementing Bubble Sort Algorithm using Java Program
- How to Fix XmlBeanDefinitionStoreException in Java SpringBoot ApplicationConfig.xml
- YAML Parser using Java Jackson Library Example
- [Fix] java: integer number too large compilation error
- Convert JSON String to Java GSON Object Example
- Read a file using Java 8 Stream
- Java Spring Boot 3 Web Hello World with Gradle in IntelliJ
- Ways Compare Dates in Java Programming with Examples
- Pretty Print JSON String in Java Console Output
- Java JDBC with Join Queries Example
- How to Check For Updates on Windows 11 (Step-by-Step)
- [Fix] java.net.MalformedURLException: unknown protocol
- How to display date and time in GMT Timezone in Java
- Error: LinkageError occurred while loading main class UnsupportedClassVersionError [Eclipse Java]
- How to convert a String to Java 8 Stream of Char?
- RabbitMQ Queue Listener Java Spring Boot Code Example
- 5+ Fibonacci number Series Java Program Examples [ 0 1 1 2 3 ..]
- Handling NullPointerException with Java Predicate
More Posts:
- How to check if a port is in use using terminal [Linux or macOS] - MacOS
- git fatal: Authentication failed error [fix] - Git
- Angular CLI ng Error: You need to specify a command before moving on. Use --help to view the available commands - HowTos
- How to know the version and Device ID of OneDrive on Mac - Windows
- Java SE JDBC Select Statement Example - Java
- Change Guest User Password of RabbitMQ - RabbitMQ
- How to change user image icon macOS Big Sur - MacOS
- [Fix] Microsoft 53003 Error - Microsoft