java delete column from csv

Solutions on MaxInterview for java delete column from csv by the best coders in the world

showing results for - "java delete column from csv"
Xavier
14 Aug 2017
1package work.basil.example;
2
3import org.apache.commons.csv.CSVFormat;
4import org.apache.commons.csv.CSVPrinter;
5import org.apache.commons.csv.CSVRecord;
6
7import java.io.BufferedReader;
8import java.io.IOException;
9import java.nio.charset.StandardCharsets;
10import java.nio.file.Files;
11import java.nio.file.InvalidPathException;
12import java.nio.file.Path;
13import java.nio.file.Paths;
14
15public class App
16{
17    public static void main ( String[] args )
18    {
19        System.out.println ( "Hello World!" );
20        App app = new App ();
21        app.demo ();
22    }
23
24    private void demo ( )
25    {
26        try
27        {
28            // Read CSV file.
29            Path pathInput = Paths.get ( "/Users/basilbourque/input.csv" );
30            Path pathOutput = Paths.get ( "/Users/basilbourque/output.csv" );
31            try (
32                    final BufferedReader reader = Files.newBufferedReader ( pathInput , StandardCharsets.UTF_8 ) ;
33                    final CSVPrinter printer = CSVFormat.RFC4180.withHeader ( "ID" , "name1" , "name3" ).print ( pathOutput , StandardCharsets.UTF_8 ) ;
34            )
35            {
36                Iterable < CSVRecord > records = CSVFormat.RFC4180.withFirstRecordAsHeader ().parse ( reader );
37                // We expect these headers: ID,name1,name2,name3
38                for ( CSVRecord record : records )
39                {
40                    // Read.
41                    Integer id = Integer.valueOf ( record.get ( "ID" ) );
42                    String name1 = record.get ( "name1" );
43                    String name2 = record.get ( "name2" );
44                    String name3 = record.get ( "name3" );
45                    System.out.println ( "id: " + id + " | name1: " + name1 + " | name2: " + name2 + " | name3: " + name3 );
46
47                    // Write.
48                    printer.printRecord ( id , name1 , name3 );
49                }
50            }
51        } catch ( InvalidPathException e )
52        {
53            e.printStackTrace ();
54        } catch ( IOException e )
55        {
56            e.printStackTrace ();
57        }
58    }
59}