代码之家  ›  专栏  ›  技术社区  ›  Blnpwr

在Java中只获得CSV的前两个位置

  •  0
  • Blnpwr  · 技术社区  · 6 年前

    我有一个包含德国汽车牌照的csv文件。结构如下: B,德国柏林 第一个字母B是城市的第一个大写字母,第二个字母是城市,第三个字母是州

    我只想要前两个职位,只有B和柏林

    我知道如何用Java读取CSV文件,但是我不知道如何告诉编译器“忽略”第三个位置。

    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]);
                }
     }
    

    输出是一个包含b、柏林和德国的数组。由于有400个板,无法手动删除csv文件中的状态。 这里的诀窍是什么?

    提前谢谢你

    [清除]

    所有元素都在同一行中: B,Berlin,Germany,M,Munich,Germany...

    5 回复  |  直到 6 年前
        1
  •  3
  •   Akceptor    6 年前

    跳过最后一行打印:

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

    如果您确定每行正好包含3个值,请执行此操作。理想情况下,这些东西应该是可配置的。一般来说,您不希望只记录这些内容,因此考虑将数据映射到某个license.class,并使用license.getletter()、license.getcity()或其他任何方法。

        2
  •  1
  •   Pradeep Bhadani    6 年前

    您可以将for循环条件更新为只读取列表的前两个元素。

    类似的东西

    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");
                }
     }
    

    希望这有帮助。

        3
  •  1
  •   aran    6 年前
    //ideally, this should be on config file
    int maxIndexToRead = 2;
    
    for(int i=0; i< maxIndexToRead;i++)
    {
         Log.d("ROWS", row[i]);
    }
    

    是的,奥尔曼风格的规则;)

        4
  •  1
  •   Basil Bourque    6 年前

    Apache Commons公司

    关于你的具体问题,其他答案是正确的。此外,下面是使用 Apache Commons CSV 图书馆,使这项工作更容易一点。

    请注意,我们如何检索这三个字段中的每一个,但只使用前两个字段,忽略第三个字段(根据您的问题)。

    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();
            }
        }
    }
    

    运行时。

    信:B市:柏林

    信:P城市:巴黎

    信:T城市:突尼斯

    按名称引用列

    或者,您可以按名称而不是按索引号引用每一列。添加标题行,并在 CSVFormat.RFC4180 寻找那些标题。

    参见上的示例代码 my Answer 类似的问题。

        5
  •  0
  •   aBnormaLz    6 年前

    如果您需要,可以取消for循环:

    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(...) {
            //...
        }
    }
    

    但是正如@akceptor在另一个答案中提到的那样,只有在您确定THA csv始终是这种格式的情况下才能这样做。

    此外,如果需要的话,使用这种方法,可以很容易地将行转换为类实例。