0

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...

AitorFDK
  • 101
  • 6
Blnpwr
  • 1,633
  • 3
  • 19
  • 36
  • 1
    you can do it yourself after split, simply don't read the 3rd index – Rajen Raiyarela Jan 04 '19 at 10:09
  • 1
    for(int i=0; i – Akceptor Jan 04 '19 at 10:09
  • It is not only B, Berlin, Germany. There are 400 plates. So if I had only B, Berlin, Germany, then I would ignore the 3rd index, but what about the 6th, 9th, 12th ... index? – Blnpwr Jan 04 '19 at 10:10
  • When you have the line splited just read the indexs that you want.. 0 and 1 in this case, always verifying that array length is correct for prevent Exception – AitorFDK Jan 04 '19 at 10:20
  • @AitorFDK that works when your csv file only contains "B, Berlin, Germany" but not when you have 400 elements in a csv fie. – Blnpwr Jan 04 '19 at 10:24
  • Ah i was interpreting you only have one element by line, so if you have all in the same line just use a counter and when you are in counter == 3 avoid this element and reset the counter. – AitorFDK Jan 04 '19 at 10:57

5 Answers5

3

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

Akceptor
  • 1,663
  • 3
  • 25
  • 27
  • Mapping every position in the csv file to a class.. yes, that's clever, but haven't got an idea how to do this – Blnpwr Jan 04 '19 at 10:17
  • Consider looking into https://stackoverflow.com/questions/6411357/java-api-to-make-an-object-from-a-csv-file and https://stackoverflow.com/questions/13505653/opencsv-how-to-map-selected-columns-to-java-bean-regardless-of-order/14976689#14976689 – Akceptor Jan 04 '19 at 10:21
1

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.

pradeep
  • 3,491
  • 6
  • 24
  • 41
1
//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 ; )

aran
  • 9,202
  • 4
  • 30
  • 62
1

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.

Community
  • 1
  • 1
Basil Bourque
  • 218,480
  • 72
  • 657
  • 915
0

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.

aBnormaLz
  • 713
  • 4
  • 19