CSV使用java删除第一行

时间:2015-03-24 16:54:51

标签: java csv

我必须设置一个java卡车应用程序,它将CSV文件从GPS转换为shapefile,我必须删除速度小于5的第一行,但一旦速度大于5,该功能应停止并且积分将正常添加。

以下是我的代码的一部分,当点被解析,添加并转换为shapefile但我仍然想知道如何删除第一行直到速度高于5 ...

    for (line = reader.readLine(); line != null; line = reader.readLine()) {
        if (line.trim().length() > 0) { // skip blank lines
            String tokens[] = line.split("\\,");
            String name1 = tokens[0].trim();
            String name2 = tokens[1].trim();
            double latitude = Double.parseDouble(tokens[2]);
            double longitude = Double.parseDouble(tokens[3]);
            String name = tokens[4].trim();
            String name4 = tokens[5].trim();

            /* Longitude (= x coord) first ! */
            Point point = geometryFactory.createPoint(new Coordinate(longitude, latitude));

            featureBuilder.add(point);
            featureBuilder.add(name1);
            featureBuilder.add(name2);
            featureBuilder.add(name);
            featureBuilder.add(name4);
            SimpleFeature feature = featureBuilder.buildFeature(null);
            features.add(feature);
        }
    }
} finally {
    reader.close();
}

1 个答案:

答案 0 :(得分:0)

好的 - 如果令牌[5]是速度,你可能需要将它从一个字符串解析为一个数字,例如Integer.parseInt(tokens [5])或Float.parseFloat(tokens [5])。然后你可以跳过你为空白所做的行,这次只有当速度小于5时。如果你只想跳过5以下的第一行,你可以为foundAnyRowHigherThan5保留一个标志。请参阅以下示例:

    boolean foundAnyRowHigherThan5 = false;
    for (line = reader.readLine(); line != null; line = reader.readLine()) {
        if (line.trim().length() > 0) { // skip blank lines
            String tokens[] = line.split("\\,");
            String name1 = tokens[0].trim();
            String name2 = tokens[1].trim();
            double latitude = Double.parseDouble(tokens[2]);
            double longitude = Double.parseDouble(tokens[3]);
            String name = tokens[4].trim();

            String speedString = tokens[5].trim();
            float speedFloat = Float.parseFloat(speedString);

          if(foundAnyRowHigherThan5 || speedFloat > 5.0) {
            // from this point forward, you will not skip lines based on speed.
            if(!foundAnyRowHigherThan5) {
              foundAnyRowHigherThan5 = true;
            }

            /* Longitude (= x coord) first ! */
            Point point = geometryFactory.createPoint(new Coordinate(longitude, latitude));

            featureBuilder.add(point);
            featureBuilder.add(name1);
            featureBuilder.add(name2);
            featureBuilder.add(name);
            featureBuilder.add(name4);
            SimpleFeature feature = featureBuilder.buildFeature(null);
            features.add(feature);
          }
       }
    }
} finally {
    reader.close();
}