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
- Error: Can not find the tag library descriptor for
- Create a Database Table using JDBC PreparedStatement
- Java JDBC Select Multiple Records from table as List using PreparedStatement
- Java Jackson with Maven Example
- [fix] Java JDBC ConnectException: Connection refused
- Spring Boot: Transactions Management with JDBCTemplate Example
- Java Get Current Date for a Specific Time Zone
- What are the 8 Primitive Data Types in Java
- Java JDBC: Insert Java 8 LocalDate and Time using PreparedStatement
- Maven Eclipse (M2e) No archetypes currently available
- How to Sort a LinkedList in Java
- [Fatal Error] XML The markup in the document following the root element must be well-formed.
- Split a String in Java with Examples
- Struts 2 : There is no Action mapped for namespace [/] and action name [form] associated with context path [/proj]
- Truncate table using Java JDBC Example
- Java: Generate random numbers within a range
- Parse XML file in Java using DOM Parser
- How to get Client IP address using Java Code Example
- JDBCTemplate Querying Examples with Spring Boot 3
- [Java Threads] Should we extend Thread Class or implement Runnable interface
- String Boot + Redis - SET and GET String Commands Examples
- Setting up Spring Boot 3 + Maven + MySQL + JDBC Example
- Spring Boot: JdbcTemplate Update Query With Parameters Example
- Java Split String by Spaces
- Unbound classpath container: JRE System Library [JavaSE-1.7]
- Insert Auto Increment Value using PreparedStatement in Java JDBC - Java
- Maven BUILD FAILURE: Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin - Java
- Error 404 Tomcat homepage http://localhost:8080/ not displayed - Tomcat
- How to install SpaCy (NLP Library) on Mac - Python
- Advanced print() Function Tutorial and Techniques for Python Developers - Python
- How to make TextView Text Transparent [Android] - Android
- Install Oh My Zsh on Ubuntu Docker complete steps - Ubuntu
- [Android Studio] Hardcoded string Button, should use @string resource - Android-Studio