In Java, you can use the java.io.BufferedReader
and java.util.StringTokenizer
classes to read and parse CSV (comma-separated values) files.
Here is an example of how to read and parse a CSV file in Java:
import java.io.BufferedReader; import java.io.FileReader; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { try (BufferedReader reader = new BufferedReader(new FileReader("data.csv"))) { String line; while ((line = reader.readLine()) != null) { StringTokenizer tokenizer = new StringTokenizer(line, ","); String name = tokenizer.nextToken(); int age = Integer.parseInt(tokenizer.nextToken()); String gender = tokenizer.nextToken(); // Process the values in the CSV file System.out.println("Name: " + name); System.out.println("Age: " + age); System.out.println("Gender: " + gender); } } catch (Exception e) { e.printStackTrace(); } } }
In this example, we use the BufferedReader
class to read the CSV file line by line, and the StringTokenizer
class to parse the values in each line. The StringTokenizer
class is used to split the line into tokens using the comma character as the delimiter. We then store the values in variables and print them to the console.
Note that this example assumes that the CSV file is structured as follows:
Name,Age,Gender John,30,Male Alice,25,Female Bob,35,Male
You can modify the code to handle different CSV file structures, such as files with headers or files with different numbers of values on each line. You can also use other techniques to parse the CSV file, such as using regular expressions or the java.util.Scanner
class.