Blnpwr
Blnpwr

Reputation: 1875

Get only the first two positions of CSV in Java

I have a csv file that contains german car license plates. The structure is as follows: B,Berlin, Germany the first one B is the first capital letter of the city, the second position is the City, and the third position is the state

I only want the first two positions, only B and Berlin

I know how to read a CSV File in Java, but I don't know how I can tell the compiler to "ignore" the third position?

public void read(){
    InputStream inputStream = getResources().openRawResource(R.raw.carplates);

    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    try {
        String csvLine;
        while ((csvLine = reader.readLine()) != null) {
            String[] row = csvLine.split(",");
            for(int i=0; i<row.length;i++){
                Log.d("ROWS", row[i]);
            }
 }

The output is an Array that contains B, Berlin and Germany. Since there are 400 plates, it is impossible to delete manually the state in the csv file. What is the trick here?

Thank you in advance

[CLEARING]

all the elements are in the same line: B,Berlin,Germany,M,Munich,Germany...

Upvotes: 0

Views: 486

Answers (5)

Basil Bourque
Basil Bourque

Reputation: 339342

Apache Commons CSV

Other Answers are correct about your specific issue. In addition, here is example code using the Apache Commons CSV library to make this work a bit easier.

Note how we retrieve each of the 3 fields, but only use the first 2, ignoring the third (per your Question).

Screenshot of the tabular data in the CityLetter.csv file, three columns and three rows for Berlin, Paris, and Tunis.

package com.basilbourque.example;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class CityLetter {
    public static void main ( String[] args ) {
        CityLetter app = new CityLetter();
        app.doit();
    }

    private void doit ( ) {
        try {
            // Locate file to import and parse.
            Path path = Paths.get( "/Users/basilbourque/CityLetter.csv" );
            if ( Files.notExists( path ) ) { System.out.println( "ERROR - no file found for path: " + path + ". Message # f31b73b0-7ba7-4ea8-81b4-c8d768dde99d." ); }

            // Read CSV file.
            // For each row, use 2 of the 3 fields (letter, city), while ignoring the third (country).
            BufferedReader reader = Files.newBufferedReader( path );
            Iterable < CSVRecord > records = CSVFormat.RFC4180.parse( reader );
            for ( CSVRecord record : records ) {
                // B,Berlin,Germany
                // P,Paris,France
                // T,Tunis,Tunisia
                String letter = record.get( 1 - 1 ); // Annoying zero-based index counting.
                String city = record.get( 2 - 1 );
                String country = record.get( 3 - 1 ); // Ignore.
                // Use the 2 of 3 values.
                System.out.println( "letter: " + letter + " | City: " + city );
//                City city = new City( letter , city );
//                listOfCities.add( city );
            }

        } catch ( IOException e ) {
            e.printStackTrace();
        }
    }
}

When run.

letter: B | City: Berlin

letter: P | City: Paris

letter: T | City: Tunis

Refer to columns by name

Alternatively, you can refer to each column by name rather than by index number. Add a header row, and add another call on the CSVFormat.RFC4180 to look for those headers.

See example code on my Answer to a similar Question.

Upvotes: 1

aBnormaLz
aBnormaLz

Reputation: 857

You can eliminate your for-loop if you want like:

public void read() {
    InputStream inputStream = getResources().openRawResource(R.raw.carplates);

    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    try {
        String csvLine;
        while((csvLine = reader.readLine()) != null) {
            String[] row = csvLine.split(",");
            Log.d("First capital letter of the city: ", row[0]);
            Log.d("City: ", row[1]);
        }
    } catch(...) {
        //...
    }
}

But as @Akceptor mentinoed in another answer, do this only if you are sure that tha CSV is always in this format.

Also with this approach you cna easily convert your row to a class instance if you want.

Upvotes: 0

aran
aran

Reputation: 11880

//ideally, this should be on config file
int maxIndexToRead = 2;

for(int i=0; i< maxIndexToRead;i++)
{
     Log.d("ROWS", row[i]);
}

And yes, Allman style rules ; )

Upvotes: 1

Akceptor
Akceptor

Reputation: 1932

Skip printing last line:

for(int i=0; i<row.length - 1; i++){
    Log.d("ROWS", row[i]);
}

Do it if you are sure each line contains exactly 3 values. Ideally this stuff should be configurable. In general you don't want just log the stuff so consider mapping data to some License.class and using license.getLetter(), license.getCity() or whatever

Upvotes: 3

Pradeep Bhadani
Pradeep Bhadani

Reputation: 4741

You can update you for loop condition to only read first two element of list you have.

Something like

public void read(){
    InputStream inputStream = getResources().openRawResource(R.raw.kfzkennzeichen);

    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    try {
        String csvLine;
        while ((csvLine = reader.readLine()) != null) {
            String[] row = csvLine.split(",");
            if (row.lenght >= 2){
               for(int i=0; i<2;i++){
                  Log.d("ROWS", row[i]);
              }
            }else{
                Log.d("Invalid Row");
            }
 }

Hope this helps.

Upvotes: 1

Related Questions