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,
- Drop table using Java JDBC Template
- Java - Check if array contains the value
- YAML Parser using Java Jackson Library Example
- Java Jackson ObjectMapper Class with Examples
- Get Client IP address from HTTP Response in Java
- How to Word-Warp Console logs in IntelliJ
- Exception in thread main java.lang.NoClassDefFoundError: package javaClass
- Setting Java_Home Environment variable on Windows Operating System
- Fix: Maven - Failed to execute goal - Compilation failure - Source/Target option 5 is no longer supported. Use 7 or later
- Java SE JDBC Select Statement Example
- How to extract Java Jar/War/Ear files in Linux
- java: unclosed string literal [Error]
- [Solution] Exception in thread main java.util.EmptyStackException
- Read YAML file Java Jackson Library
- What Java version is used for Minecraft 1.18
- [Java] How to throws Exception using Functional Interface and Lambda code
- [Program] How to read three different values using Scanner in Java
- Java 8 Predicate Functional Interface Examples
- Display Era details (AD BC) in Java Date using SimpleDateFormat
- Convert String Date to Date Object in Java
- Struts 2 Hello World Example in Eclipse
- Read a file using Java 8 Stream
- Java - How to set custom thread name?
- IntelliJ: Error: Could not find or load main class, java.lang.ClassNotFoundException
- java: ']' expected error [fixed]
More Posts:
- Share Story Feed on Facebook using URL - Facebook
- Create Safari Shortcut on Mac Desktop - MacOS
- How to turn on Bluetooth on Windows 10 - Microsoft
- Notepad++ copy above line-example - NotepadPlusPlus
- ModuleNotFoundError: No module named qdarkstyle.colorsystem [Python] - Python
- How to show or hide columns in SharePoint Online List Library from - SharePoint
- Update SharePoint Online List Item using REST API, HTML, Spfx, Postman - SharePoint
- Restore deleted Office 365 SharePoint group site - SharePoint