java读取csv文件_使用扫描仪读取Java中的CSV文件

这篇博客介绍了如何利用Java的Scanner类读取CSV文件,并将其转换为Java Bean的集合。通过设置分隔符,可以解析不同分隔符的CSV文件。运行示例程序后,将输出读取的CSV文件内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java读取csv文件

We can use Java Scanner Class to read CSV File in java.

我们可以使用Java扫描程序类在Java中读取CSV文件。

读取Java中的CSV文件 (Read CSV File in Java)

We can use Java Scanner class to read CSV file and convert to collection of java bean. For example, we might have a CSV file like below.

我们可以使用Java Scanner类读取CSV文件并将其转换为Java bean的集合。 例如,我们可能有一个如下所示的CSV文件。

employees.csv

employees.csv

1,Pankaj Kumar,Developer,5000 USD
2,Mani,Programmer,4000 USD
3,Avinash,Developer,5000 USD
4,David,QA Lead,4000 USD

And we have a java bean that maps to different columns in the CSV file.

我们有一个Java Bean,它映射到CSV文件中的不同列。

Employee.java

Employee.java

package com.journaldev.csv;

public class Employee {

	private int id;
	private String name;
	private String role;
	private String salary;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getRole() {
		return role;
	}
	public void setRole(String role) {
		this.role = role;
	}
	public String getSalary() {
		return salary;
	}
	public void setSalary(String salary) {
		this.salary = salary;
	}
	
	@Override
	public String toString(){
		return "\nID="+getId()+"::Name"+getName()+"::Role="+getRole()+"::Salary="+getSalary();
	}
}

Let’s say that employee bean variables maps to following columns in CSV file.

假设员工bean变量映射到CSV文件中的以下列。

1st Column – Employee ID
2nd Column – Employee Name
3rd Column – Employee Role
4th Column – Employee Salary

第一栏–员工编号
第二栏–员工姓名
第三栏–员工角色
第四栏–员工薪水

Now we can use Scanner class to parse CSV file and create collection of Employees.

现在,我们可以使用Scanner类来解析CSV文件并创建员工集合。

ReadCSVWithScanner.java

ReadCSVWithScanner.java

package com.journaldev.csv;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class ReadCSVWithScanner {

	public static void main(String[] args) throws IOException {
		// open file input stream
		BufferedReader reader = new BufferedReader(new FileReader(
				"employees.csv"));

		// read file line by line
		String line = null;
		Scanner scanner = null;
		int index = 0;
		List<Employee> empList = new ArrayList<>();

		while ((line = reader.readLine()) != null) {
			Employee emp = new Employee();
			scanner = new Scanner(line);
			scanner.useDelimiter(",");
			while (scanner.hasNext()) {
				String data = scanner.next();
				if (index == 0)
					emp.setId(Integer.parseInt(data));
				else if (index == 1)
					emp.setName(data);
				else if (index == 2)
					emp.setRole(data);
				else if (index == 3)
					emp.setSalary(data);
				else
					System.out.println("invalid data::" + data);
				index++;
			}
			index = 0;
			empList.add(emp);
		}
		
		//close reader
		reader.close();
		
		System.out.println(empList);
		
	}

}

Notice that we are setting scanner delimiter as comma (,). If input file uses some other delimiter such as pipe (|) or hash (#), then all we need to do is change the delimiter pattern in above program.

请注意,我们将扫描仪定界符设置为逗号(,)。 如果输入文件使用其他分隔符,例如竖线(|)或哈希(#),那么我们所需要做的就是更改上述程序中的分隔符模式。

Once we run above program, it prints following output.

一旦我们运行了上面的程序,它将打印以下输出。

[
ID=1::NamePankaj Kumar::Role=Developer::Salary=5000 USD, 
ID=2::NameMani::Role=Programmer::Salary=4000 USD, 
ID=3::NameAvinash::Role=Developer::Salary=5000 USD, 
ID=4::NameDavid::Role=QA Lead::Salary=4000 USD]

If you look into Scanner class constructor, you will notice that it accepts File or InputStream as input. Also it contains utility method hasNextLine() and nextLine() that we can use to parse CSV file using Scanner only.

如果查看Scanner类的构造函数,您会注意到它接受File或InputStream作为输入。 它还包含实用程序方法hasNextLine()nextLine() ,我们只能使用Scanner来解析CSV文件。

CSVScannerExample.java

CSVScannerExample.java

package com.journaldev.csv;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class CSVScannerExample {

	public static void main(String[] args) throws IOException {
		Scanner scanner = new Scanner(new File("employees.csv"));
		Scanner dataScanner = null;
		int index = 0;
		List<Employee> empList = new ArrayList<>();
		
		while (scanner.hasNextLine()) {
			dataScanner = new Scanner(scanner.nextLine());
			dataScanner.useDelimiter(",");
			Employee emp = new Employee();

			while (dataScanner.hasNext()) {
				String data = dataScanner.next();
				if (index == 0)
					emp.setId(Integer.parseInt(data));
				else if (index == 1)
					emp.setName(data);
				else if (index == 2)
					emp.setRole(data);
				else if (index == 3)
					emp.setSalary(data);
				else
					System.out.println("invalid data::" + data);
				index++;
			}
			index = 0;
			empList.add(emp);
		}

		scanner.close();

		System.out.println(empList);

	}

}

If you run above program, the output produced will be same as above program. Scanner class is a good choice if all you need is to parse a simple CSV file.

如果您运行上述程序,则产生的输出将与上述程序相同。 如果您只需要解析一个简单的CSV文件,则扫描仪类是一个不错的选择。

翻译自: https://www.journaldev.com/2335/read-csv-file-java-scanner

java读取csv文件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值