读入每一行的每一列值,只写出需要的列,跳过不需要的列值。
使用 Apache Commons CSV 库的示例应用程序
这是一个示例应用程序,演示如何使用 Apache Commons CSV 读取输入文件,然后写入输出文件,跳过不需要的列值。
注意使用 try-with-resources 语法来自动关闭我们的文件读取器和写入器对象。见Tutorial by Oracle。
RFC 4180 指的是定义Comma-Separated Values (CSV) 格式的书面标准。
创建一个名为input.csv的文件。
ID,name1,name2,name3
1,hello,hell,hel
2,try,tr,t
3,browser,ro,br
Java 应用程序。
package work.basil.example;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
public class App
{
public static void main ( String[] args )
{
System.out.println ( "Hello World!" );
App app = new App ();
app.demo ();
}
private void demo ( )
{
try
{
// Read CSV file.
Path pathInput = Paths.get ( "/Users/basilbourque/input.csv" );
Path pathOutput = Paths.get ( "/Users/basilbourque/output.csv" );
try (
final BufferedReader reader = Files.newBufferedReader ( pathInput , StandardCharsets.UTF_8 ) ;
final CSVPrinter printer = CSVFormat.RFC4180.withHeader ( "ID" , "name1" , "name3" ).print ( pathOutput , StandardCharsets.UTF_8 ) ;
)
{
Iterable < CSVRecord > records = CSVFormat.RFC4180.withFirstRecordAsHeader ().parse ( reader );
// We expect these headers: ID,name1,name2,name3
for ( CSVRecord record : records )
{
// Read.
Integer id = Integer.valueOf ( record.get ( "ID" ) );
String name1 = record.get ( "name1" );
String name2 = record.get ( "name2" );
String name3 = record.get ( "name3" );
System.out.println ( "id: " + id + " | name1: " + name1 + " | name2: " + name2 + " | name3: " + name3 );
// Write.
printer.printRecord ( id , name1 , name3 );
}
}
} catch ( InvalidPathException e )
{
e.printStackTrace ();
} catch ( IOException e )
{
e.printStackTrace ();
}
}
}
控制台输出。
id: 1 |姓名1:你好| name2:地狱 | name3: 帮助
id: 2 |名称1:尝试|名称2:tr | name3: t
id: 3 | name1: 浏览器 | name2: 罗 |名称3:br
生成的文件名为 output.csv。
ID,name1,name3
1,hello,hel
2,try,t
3,browser,br