如果CSV项目不在引号中,如何引发异常

时间:2020-07-16 12:28:23

标签: java csv opencsv

我正在使用打开的csv来解析和读取csv文件

void initClosingAnimation() { ObservableList<Node> components = window.getScene().getRoot().getChildrenUnmodifiable(); time = new Timeline(); Duration startTime = Duration.ZERO ; Duration endTime = Duration.seconds(0.4); Duration offset = Duration.seconds(0.1); for (Node component : components) { KeyValue startValue = new KeyValue(component.translateXProperty(), component.getTranslateX(), Interpolator.EASE_OUT); KeyValue endValue = new KeyValue(component.translateXProperty(), window.getWidth(), Interpolator.EASE_OUT); KeyFrame start = new KeyFrame(startTime, startValue); KeyFrame end = new KeyFrame(endTime, endValue); time.getKeyFrames().add(start); time.getKeyFrames().add(end); startTime = startTime.add(offset); endTime = endTime.add(offset); } time.play(); } 的内容->

import javafx.animation.Interpolator;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.stage.Window;
import javafx.util.Duration;


public class App extends Application {

    @Override
    public void start(Stage stage) {
        VBox root = new VBox(5);
        root.setAlignment(Pos.CENTER);
        for (int i = 1 ; i <= 10 ; i++) root.getChildren().add(new Label("Item "+i));
        Button close = new Button("Close");
        root.getChildren().add(close);
        close.setOnAction(e -> initClosingAnimation(stage, stage::hide));
        Scene scene = new Scene(root, 400, 600);
        stage.setScene(scene);
    
        stage.setOnCloseRequest(e -> {
            initClosingAnimation(stage, stage::hide);
            e.consume();
        });
    
        stage.show();
    }
    
    private void initClosingAnimation(Window window, Runnable onFinished) {
        ObservableList<Node> components = window.getScene().getRoot().getChildrenUnmodifiable();
        Timeline time = new Timeline();

        Duration startTime = Duration.ZERO ;
        Duration endTime = Duration.seconds(0.4);

        Duration offset = Duration.seconds(0.1);
        
        for (Node component : components) {
            KeyValue startValue = new KeyValue(component.translateXProperty(), component.getTranslateX(), Interpolator.EASE_OUT);
            KeyValue endValue = new KeyValue(component.translateXProperty(), window.getWidth(), Interpolator.EASE_OUT);
            KeyFrame start = new KeyFrame(startTime, startValue);
            KeyFrame end = new KeyFrame(endTime, endValue);
            time.getKeyFrames().add(start);
            time.getKeyFrames().add(end);
            startTime = startTime.add(offset);
            endTime = endTime.add(offset);
        }
        time.setOnFinished(e -> onFinished.run());
        time.play();
    }

    public static void main(String[] args) {
        launch();
    }

}

如果任何CSV项都不用双引号引起来,我想抛出一个异常。在我的CSV文件中,test.csv不在双引号中。

但是当前的"COL_1","COL_2",COL_3 给出的第三条记录为空白。

解析器->

COL_3

2 个答案:

答案 0 :(得分:0)

解析器/读取器本身不知道应该有多少列以及必须如何填充它们。

如果要检查已解析数据的结构,则必须手动执行。

所以也许您想添加类似的内容:

while ((line = csvReader.readNext()) != null) {
    if (line.length < 3) {
        throw new ParsingException();
    }
}

答案 1 :(得分:0)

CSVParser上的.withStrictQuotes(true)选项导致引号字符之外的字符被忽略,因此示例中的第三列将被忽略。我发现使用OpenCsv的唯一方法(基本上无需重写解析,您可以通过提供行验证器来完成此操作)是将引号字符设置为不会出现在数据中的内容,并设置.withStrictQuotes(false),如下所示:

    public void test1() {
        CSVParser parser = new CSVParserBuilder()
                .withSeparator(',')
                .withQuoteChar('?')
                .withStrictQuotes(false)
                .withIgnoreQuotations(true)
                .build();

        try {
            File file = new File(this.getClass().getClassLoader().getResource("csv_test.csv").getFile());
            try (FileReader fileReader = new FileReader(file)){
                CSVReader csvReader = new CSVReaderBuilder(fileReader)
                            .withCSVParser(parser)
                            .withKeepCarriageReturn(false)
                            .build() ;
                String[] line;
                while((line = csvReader.readNext()) != null) {
                    if (validate(line)) {
                        processLine(line);
                    } else {
                        throw new Exception("invalid line");
                    }
                }
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    private boolean validate(String[] line) {
        boolean isValid = true;
        for (String field: line) {
            if (field.length() > 1 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
                isValid &= true;
            } else {
                isValid = false;
                System.out.println("error with field: " + field);
            }
        }
        return isValid;
    }
    
    private void processLine(String[] line) {
        System.out.println(line);
    }