在Java中处理CSV文件
CSV是逗号分隔值的缩写。它是一种文档设计,用于将会计页面或数据集中的信息保持在一个简单的文本结构中。分隔符被用来识别和隔离逗号分隔值中的信息。
简介
CSV记录设计在本地工作的不协调组织的程序之间移动结构化信息。
前提条件
要想跟上,读者应该。
- 有Java的基本知识。
- 安装一个你选择的IDE。我将使用EclipseIDE。
创建CSV文件
微软Excel办公室
- 首先,在你的电脑上打开Excel办公室。
- 其次,打开一个空白工作簿。然后将下面的信息输入Excel文件。

- 将Excel文件保存为CSV(逗号分隔)。将文件命名为逗号分隔的,并完成保存。

记事本
- 让我们从打开记事本开始。
- 其次,输入如下所示的信息。记住要用逗号来分隔每个数据。
Student Name,Faculty,Registration No,Fees Balance,Campus
Stanley Kuria,Education,37916808,3150,Main
Davidson Kanyua,Computing,38094044,8500,Meru
Tess Wambui,Engineering,21666504,13500,Nairobi
Esther Njoroge,Health,37809504,5500,Nakuru
- 然后将该文件保存为
commaseperated.csv。我们创建的文件应该看起来像下面的文件。

Java String.split()技术
String.split,应用于在给定的标准衔接的周围断开字符串的匹配。在下面的代码中,我们导入了BufferedReader 。BufferedReader ,逐行读取文件到最后。
import java.io.FileReader;
import java.io.IOException;//signals an exception of some kind has occurred
import java.io.BufferedReader;//Reads text from a character-input stream
class readcsv
{
public static void main(String[] args)
{
String sample = ",";
String mystring;
try
{
BufferedReader brdrd = new BufferedReader(new FileReader("C:\\Users\\davis\\eclipse-workspace\\CSVdocuments\\commaseperated.csv"));
while ((mystring = brdrd.readLine()) != null) //Reads a line of text
{
String[] student = mystring.split(sample);//utilized to split the string
System.out.println("Name: " + student[0] + ",Faculty: " + student[1] + ", Registration No: " + student[2] + ", Fees Balance: " + student[3] + ", Campus: " + student[4] +"");
}
}
catch (IOException e)//catches exception in the try block
{
e.printStackTrace();//Prints this throwable and its backtrace
}
}
}
该代码的输出如下所示。
Name: Student Name,Faculty: Faculty, Registration: Registration No, Fees Balance: Fees Balance, Campus: Campus
Name: Stanley Kuria,Faculty: Education, Registration: 37916808, Fees Balance: 3150, Campus: Main
Name: Davidson Kanyua,Faculty: Computing, Registration: 38094044, Fees Balance: 8500, Campus: Meru
Name: Tess Wambui,Faculty: Engineering, Registration: 21666504, Fees Balance: 13500, Campus: Nairobi
Name: Esther Njoroge,Faculty: Health, Registration: 37809504, Fees Balance: 5500, Campus: Nakuru
Java扫描器类
这是Java.util 捆绑包中的一个类,用于从用户那里获得输入。它利用分隔符模式,将信息分解成标记。这是在Java代码中读取输入的最直接的方法。
在下面的代码中,我们使用扫描器类来读取Java中的CSV文件。
import java.util.Scanner;//contains scanner class
import java.io.*;
class mycsvread
{
public static void main(String[] args) throws FileNotFoundException //This exception will be thrown when a file with the specified pathname does not exist
{
Scanner myscanner = new Scanner(new File("C:\\Users\\davis\\eclipse-workspace\\CSVdocuments\\commaseperated.csv"));//Creates a new File
myscanner.useDelimiter(", "); //Sets the delimiter
while (myscanner.hasNext()) //Returns a boolean(true) if this scanner has another token in its input
{
System.out.println(myscanner.next());//next complete scanner is returned here
}
myscanner.close(); //myscanner is closed
}
}
输出结果如下图所示。
Student Name,Faculty,Registration No,Fees Balance,Campus
Stanley Kuria,Education,37916808,3150,Main
Davidson Kanyua,Computing,38094044,8500,Meru
Tess Wambui,Engineering,21666504,13500,Nairobi
Esther Njoroge,Health,37809504,5500,Nakuru
使用openCSV API
OpenCSV是一个外部的API,用来浏览不同的逗号分隔文件的改编。它支持所有基本的逗号分隔的操作。使用OpenCSV是因为Java没有提供本地支持来读取逗号分隔的值。
重要的OpenCSV类
CSVWrite- 能够将数据写入CSV文件。CSVToBean- 用于用CSV数据填充Java应用程序。BeanToCSV- 用于将信息从JavaBean导出到逗号分隔值文件。
逗号分隔值的读取方式主要有两种。
- 按行。在这种情况下,逗号分隔的值从一行连续读到另一行。
- 所有数据:利用
readAll()技术,一次性浏览所有记录。
Example: List allData = csvReader.readAll();
打开CSV的语法。public CSVReader(Reader reader, char separator)
在Java中读取CSV文件
第1步
在eclipse-workspace中创建两个文件夹,并命名为CSVDoc 和CSVdocuments 。在CSVdocuments 文件夹中,移动你将使用的CSV文件。在这种情况下,我们将使用逗号分隔的和分号分隔的文件。
然后在CSVDoc 文件夹中粘贴opencsv-5.5.2 和commons-lang3-3.1 jar 文件。如果你没有这些文件,请点击opencsv5.5.2和commonlangs3-3.1下载它们。

第2步
打开Eclipse,并创建一个Java项目。将该项目命名为CSVOperation ,然后点击下一步。

第3步
点击Libraries ,选择Classpath 。然后选择add external Jars ,在Eclipse-workspace文件夹中添加CSVDoc的jars。然后点击完成。



第4步
之后,创建一个Java类。右键单击项目CSVOperation,选择新建,然后选择类。

第5步
将该类命名为ReadCSVExample ,然后点击完成。

第6步
然后复制下面的代码样本并粘贴。运行该程序。
import com.opencsv.CSVReader;//external library
import java.io.FileReader; //Reads text from character files using a default buffer size
public class ReadCSVExample
{
private static String LOCATION_OF_THE_FILE="C:\\Users\\davis\\eclipse-workspace\\CSVdocuments\\commaseperated.csv";//file location
public static void main(String[] args)
{
LineByLine(LOCATION_OF_THE_FILE);
}
public static void LineByLine(String myfile)
{
try
{
FileReader freader= new FileReader(myfile);//created an object of freader class
@SuppressWarnings("resource")
CSVReader creader= new CSVReader(freader);// created creader object by parsing freader as a parameter
String [] nextRecord;// created an array of type String
//read data line by line
while((nextRecord = creader.readNext())!=null)
{
for(String token: nextRecord)
System.out.println(token +"\t"); //will bring the value of cell seperated by tab space
}
System.out.println();
}
catch(Exception e) //to catch any exception inside try block
{
e.printStackTrace();//used to print a throwable class along with other dataset class
}
}
}
输出应该类似于下面的代码。
Student Name
Faculty
Registration No
Fees Balance
Campus
Stanley Kuria
Education
37916808
3150
Main
Davidson Kanyua
Computing
38094044
8500
Meru
Tess Wambui
Engineering
21666504
13500
Nairobi
Esther Njoroge
Health
37809504
5500
Nakuru
你会注意到没有逗号。这是因为在使用开放的CSV API时,逗号被忽略了。
让我们实现一个程序来读取一个没有逗号分隔的CSV文件。而是用分号(;)分开。
我们要读取的CSV文件如下所示。

复制下面的程序并粘贴和运行它。
import com.opencsv.CSVReader;//external library
import java.io.FileReader; //Reads text from character files using a default buffer size
public class ReadCSVExample
{
private static String LOCATION_OF_THE_FILE="C:\\Users\\davis\\eclipse-workspace\\CSVdocuments\\semicolonseperated.csv";//file location
public static void main(String[] args)
{
LineByLine(LOCATION_OF_THE_FILE);
}
public static void LineByLine(String myfile)
{
try
{
FileReader freader= new FileReader(myfile);//created an object of freader class
@SuppressWarnings("resource")
CSVReader creader= new CSVReader(freader);// created creader object by parsing freader as a parameter
String [] nextRecord;// created an array of type String
//read data line by line
while((nextRecord = creader.readNext())!=null)
{
for(String token: nextRecord)
System.out.println(token +"\t"); //will bring the value of cell seperated by tab space
}
System.out.println();
}
catch(Exception e) //to catch any exception inside try block
{
e.printStackTrace();//used to print a throwable class along with other dataset class
}
}
}
输出结果如下图所示。
Student Name;Faculty;Registration No;Fees Balance;Campus
Stanley Kuria;Education;37916808;3150;Main
Davidson Kanyua;Computing;38094044;8500;Meru
Tess Wambui;Engineering;21666504;13500;Nairobi
Esther Njoroge;Health;37809504;5500;Nakuru
在上面的输出中,你会注意到分号分隔符的存在。这是因为OpenCSV忽略了逗号,但其他分隔符是可以识别的。
总结
本文重点介绍了在Java中创建CSV文件的各种技术。我们还学习了在Java中读取逗号分隔值(CSV)的不同方法。最后,我们使用开放的CSV API来读取CSV文件。