【问题标题】:How to ignore lines starting with tilde symbol"~" while parsing?解析时如何忽略以波浪号“~”开头的行?
【发布时间】:2016-01-05 05:38:43
【问题描述】:

对于所有以波浪号开头的子类~我想忽略整行

 ~ public void visitMethod(org.apache.bcel.classfile.Method arg0): 4

我想忽略所有以“~”开头的行

这是我正在解析的文本文件

gr.spinellis.ckjm.ClassVisitor 13 2 0 14 74 34 2 14 9 0.6042 431 0.8750 1 0.7273 0.2404 0 0 31.5385
 ~ public void visitMethod(org.apache.bcel.classfile.Method arg0): 4
 ~ public void registerCoupling(String arg0): 4
 ~ public void end(): 5
 ~ public void <init>(org.apache.bcel.classfile.JavaClass arg0, gr.spinellis.ckjm.ClassMetricsContainer arg1): 1
 ~ public gr.spinellis.ckjm.ClassMetrics getMetrics(): 1
 ~ private void incRFC(String arg0, String arg1, org.apache.bcel.generic.Type[] arg2): 1
 ~ public void start(): 1
 ~ void registerMethodInvocation(String arg0, String arg1, org.apache.bcel.generic.Type[] arg2): 1
 ~ public void visitField(org.apache.bcel.classfile.Field arg0): 1
 ~ public void visitJavaClass(org.apache.bcel.classfile.JavaClass arg0): 5
 ~ void registerFieldAccess(String arg0, String arg1): 2
 ~ static String className(org.apache.bcel.generic.Type arg0): 3
 ~ public void registerCoupling(org.apache.bcel.generic.Type arg0): 1

gr.spinellis.ckjm.ClassMetricsContainer 3 1 0 4 18 0 2 3 2 0.0000 66 1.0000 0 0.0000 0.5556 0 0 20.6667
 ~ void <init>(): 1
 ~ public gr.spinellis.ckjm.ClassMetrics getMetrics(String arg0): 2
 ~ public void printMetrics(gr.spinellis.ckjm.CkjmOutputHandler arg0): 3

gr.spinellis.ckjm.MetricsFilter 7 1 0 6 30 11 2 6 5 0.6667 218 1.0000 0 0.0000 0.2000 0 0 29.8571
 ~ public static boolean isJdkIncluded(): 1
 ~ static void processClass(gr.spinellis.ckjm.ClassMetricsContainer arg0, String arg1): 3
 ~ public static void runMetrics(String[] arg0, gr.spinellis.ckjm.CkjmOutputHandler arg1): 2
 ~ public static boolean includeAll(): 2
 ~ static void <clinit>(): 1
 ~ public static void main(String[] arg0): 7
 ~ public void <init>(): 1

gr.spinellis.ckjm.PrintPlainResults 2 1 0 3 8 0 1 2 2 0.0000 24 1.0000 0 0.0000 0.6250 0 0 10.5000
 ~ public void handleClass(String arg0, gr.spinellis.ckjm.ClassMetrics arg1): 1
 ~ public void <init>(java.io.PrintStream arg0): 1

gr.spinellis.ckjm.MethodVisitor 11 2 0 21 40 0 1 21 8 0.5500 209 1.0000 1 0.9474 0.1736 0 0 17.6364
 ~ public void visitINSTANCEOF(org.apache.bcel.generic.INSTANCEOF arg0): 1
 ~ public void visitLocalVariableInstruction(org.apache.bcel.generic.LocalVariableInstruction arg0): 2
 ~ public void visitCHECKCAST(org.apache.bcel.generic.CHECKCAST arg0): 1
 ~ private boolean visitInstruction(org.apache.bcel.generic.Instruction arg0): 4
 ~ public void visitInvokeInstruction(org.apache.bcel.generic.InvokeInstruction arg0): 2
 ~ public void visitReturnInstruction(org.apache.bcel.generic.ReturnInstruction arg0): 1
 ~ public void visitArrayInstruction(org.apache.bcel.generic.ArrayInstruction arg0): 1
 ~ public void visitFieldInstruction(org.apache.bcel.generic.FieldInstruction arg0): 1
 ~ void <init>(org.apache.bcel.generic.MethodGen arg0, gr.spinellis.ckjm.ClassVisitor arg1): 1
 ~ public void start(): 5
 ~ private void updateExceptionHandlers(): 3

gr.spinellis.ckjm.CkjmOutputHandler 1 1 0 4 1 0 3 1 1 2.0000 1 0.0000 0 0.0000 1.0000 0 0 0.0000
 ~ public abstract void handleClass(String, 

gr.spinellis.ckjm.ClassMetrics): 1

这是我的完整代码

          package javaapplication59;


        import java.io.BufferedReader;
        import java.io.IOException;
        import java.nio.charset.StandardCharsets;
        import java.nio.file.Files;
        import java.nio.file.Path;
        import java.nio.file.Paths;
        import java.util.ArrayList;
        import java.util.List;

        import javafx.application.Application;
        import static javafx.application.Application.launch;
        import javafx.beans.InvalidationListener;
        import javafx.beans.Observable;
        import javafx.beans.property.SimpleDoubleProperty;
        import javafx.beans.property.SimpleIntegerProperty;
        import javafx.beans.property.SimpleStringProperty;
        import javafx.collections.FXCollections;
        import javafx.collections.ObservableList;
        import javafx.event.ActionEvent;
        import javafx.event.Event;
        import javafx.event.EventHandler;
        import javafx.geometry.Pos;
        import javafx.scene.Group;
        import javafx.scene.Scene;
        import javafx.scene.chart.PieChart;
        import javafx.scene.control.Button;
        import javafx.scene.control.SelectionMode;
        import javafx.scene.control.TableColumn;
        import javafx.scene.control.TableView;
        import javafx.scene.control.TableView.TableViewSelectionModel;
        import javafx.scene.control.cell.PropertyValueFactory;
        import javafx.scene.layout.HBox;
        import javafx.scene.layout.VBox;
        import javafx.scene.paint.Color;
        import javafx.scene.text.Text;
        import javafx.stage.Stage;

    public class Javajavaapplication59Table extends Application {

    public TableView<Metrics> tableView = new TableView<Metrics>();
    private ObservableList<Metrics> dataList = FXCollections
                    .observableArrayList(


                    );

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

    @Override
    public void start(Stage primaryStage) {

    primaryStage.setTitle("JAVA JAVA JAVA m");
    VBox root = new VBox();



    TableColumn name = new TableColumn("name");
    name.setCellValueFactory(new PropertyValueFactory<Metrics, String>("name"));

    TableColumn WMCCol = new TableColumn("WMC");
    WMCCol.setCellValueFactory(new PropertyValueFactory<Metrics, Double>("WMC"));

    TableColumn DITCol = new TableColumn("DIT");
    DITCol.setCellValueFactory(new PropertyValueFactory<Metrics, Double>("DIT"));

    TableColumn NOCCol = new TableColumn("NOC");
    NOCCol.setCellValueFactory(new PropertyValueFactory<Metrics, Double>("NOC"));
    TableColumn CBOCol = new TableColumn("CBO");
    CBOCol.setCellValueFactory(new PropertyValueFactory<Metrics, Double>("CBO"));
    TableColumn RFCCol = new TableColumn("RFC");
    RFCCol.setCellValueFactory(new PropertyValueFactory<Metrics, Double>("RFC"));
    TableColumn LCOMCol = new TableColumn("LCOM");
    LCOMCol.setCellValueFactory(new PropertyValueFactory<Metrics, Double>(  "LCOM"));
    TableColumn ceCol = new TableColumn("Ca");
    ceCol.setCellValueFactory(new PropertyValueFactory<Metrics, Double>("ce"));
    TableColumn NPMCol = new TableColumn("NPM");
    NPMCol.setCellValueFactory(new PropertyValueFactory<Metrics, Double>("NPM"));


    // CaCol,LCOM3Col,LOCCol,DAMCol,MOACol,MFACol,CAMCol,ICCol,CBMCCol,AMCCol,CCCol,SUB_NAMECol
    TableColumn CaCol = new TableColumn("Ca");
    CaCol.setCellValueFactory(new PropertyValueFactory<Metrics, Double>("Ca"));

    TableColumn LCOM3Col = new TableColumn("LCOM3");
    LCOM3Col.setCellValueFactory(new PropertyValueFactory<Metrics, Double>("LCOM3"));

    TableColumn LOCCol = new TableColumn("LOC");
    LOCCol.setCellValueFactory(new PropertyValueFactory<Metrics, Double>("LOC"));

    TableColumn DAMCol = new TableColumn("DAM");
    DAMCol.setCellValueFactory(new PropertyValueFactory<Metrics, Double>(   "DAM"));

    TableColumn MOACol = new TableColumn("MOA");
    MOACol.setCellValueFactory(new PropertyValueFactory<Metrics, Double>("MOA"));

    TableColumn MFACol = new TableColumn("MFA");
    MFACol.setCellValueFactory(new PropertyValueFactory<Metrics, Double>("MFA"));

    TableColumn CAMCol = new TableColumn("CAM");
    CAMCol.setCellValueFactory(new PropertyValueFactory<Metrics, Double>("CAM"));

    TableColumn ICCol = new TableColumn("IC");
    ICCol.setCellValueFactory(new PropertyValueFactory<Metrics, Double>("IC"));

    TableColumn CBMCCol = new TableColumn("CBM");
    CBMCCol.setCellValueFactory(new PropertyValueFactory<Metrics, Double>("CBM"));

    TableColumn AMCCol = new TableColumn("AMC");
    AMCCol.setCellValueFactory(new PropertyValueFactory<Metrics, Double>(   "AMC"));



    primaryStage.setScene(new Scene(root));
    primaryStage.show();

    List<Metrics> metric = readMetricFromCSV("C:\\Users\\hp\\Desktop\\101.txt");
    // let's print all the metric read from CSV file
    for (Metrics m : metric) {
            System.out.println(m);

    }

    tableView.setItems(FXCollections.observableArrayList(metric));
    tableView.getColumns().addAll(name, WMCCol, DITCol, NOCCol, CBOCol,
                    RFCCol, LCOMCol, ceCol, NPMCol,CaCol,LCOM3Col,LOCCol,DAMCol,MOACol,MFACol,CAMCol,ICCol,CBMCCol,AMCCol);

    VBox vBox = new VBox();

    vBox.setSpacing(10);


    HBox boxc = new HBox();
    vBox.prefWidthProperty().bind(root.prefWidthProperty());
    boxc.setManaged(true);
    boxc.getChildren().addAll( tableView);
    vBox.getChildren().add(boxc);

    HBox hbox = new HBox();



    root.getChildren().add(vBox);
    root.getChildren().add(hbox);

    }

    public List<Metrics> readMetricFromCSV(String fileName) {

    List<Metrics> metricsss = new ArrayList<>();

    Path pathToFile = Paths.get(fileName);
    // create an instance of BufferedReader
    // using try with resource, Java 7 feature to close resources
    try (BufferedReader br = Files.newBufferedReader(pathToFile,
    StandardCharsets.US_ASCII)) {
    // read the first line from the text file
    String line = br.readLine();
    while (line != null && !line.isEmpty()) { // loop until all lines

         if (line.contains("~ ")) {
  continue;
}
                                                    // are read
    String[] attributes = line.split(" "); // the file, using a  comma as the  delimiter first  18 values

    Metrics valueOfMetric = createMetric(attributes);          
    metricsss.add(valueOfMetric); // adding metric into ArrayList
    br.readLine();
    line = br.readLine();
        }

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

    return metricsss;
    }

        private Metrics createMetric(String[] metadata) {
    String name = metadata[0];
    int WMC = Integer.parseInt(metadata[1]);
    int DIT = Integer.parseInt(metadata[2]);
    int NOC = Integer.parseInt(metadata[3]);
    int CBO = Integer.parseInt(metadata[4]);
    int RFC = Integer.parseInt(metadata[5]);
    int LCOM = Integer.parseInt(metadata[6]);
    int Ce   = Integer.parseInt(metadata[7]);
    int NPM = Integer.parseInt(metadata[8]);

    int Ca =Integer.parseInt(metadata[9]);
    Double LCOM3 =Double.parseDouble(metadata[10]);
    int LOC =Integer.parseInt(metadata[11]);
    Double DAM =Double.parseDouble(metadata[12]);
    int MOA =Integer.parseInt(metadata[13]);
    Double MFA  =Double.parseDouble(metadata[14]);
    Double CAM =Double.parseDouble(metadata[15]);
    int IC =Integer.parseInt(metadata[16]);
    int CBM  =Integer.parseInt(metadata[17]); 
    Double AMC =Double.parseDouble(metadata[18]);


                return new Metrics(  name, WMC, DIT, NOC, CBO, RFC, LCOM,  Ce,  NPM,   Ca,
                     LCOM3, LOC, DAM, MOA, MFA, CAM, IC, CBM , AMC ) ;
        }





    public class Metrics {

    private String name;
    private int WMC;
    private int DIT;
    private int NOC;
    private int CBO;
    private int RFC;
    private int LCOM;
    private int Ce;
    private int NPM;
    private int Ca;
    private Double LCOM3;
    private int LOC;
    private Double DAM;
    private int MOA;
    private Double MFA;
    private Double CAM;
    private int IC;
    private int CBM ;
    private Double AMC;
    private int CC;
    private String SUB_NAME;

    public Metrics( String name,int WMC,int DIT,int NOC,int CBO,int RFC,int LCOM, int Ce, int NPM,  int Ca,
                    Double LCOM3,int LOC,Double DAM,int MOA,Double MFA,Double CAM,int IC,int CBM ,Double AMC ) {

        this.name = name;
        this.WMC = WMC;
        this.DIT = DIT;
        this.NOC = NOC;
        this.CBO = CBO;
        this.RFC = RFC;
        this.LCOM = LCOM;
        this.Ce = Ce;
        this.NPM = NPM;
        this. Ca =Ca;
        this. LCOM3 =LCOM3;
        this. LOC =LOC;
        this. DAM =DAM;
        this. MOA =MOA;
        this. MFA =MFA;
        this. CAM =CAM;
        this. IC =IC;
        this.CBM  =CBM;
        this. AMC =AMC;

    }


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getWMC() {
        return WMC;
    }

    public void setWMC(int WMC) {
        this.WMC = WMC;
    }

    public int getDIT() {
        return DIT;
    }

    public void setDIT(int DIT) {
        this.DIT = DIT;
    }

    public int getNOC() {
        return NOC;
    }

    public void setNOC(int NOC) {
        this.NOC = NOC;
    }

    public int getCBO() {
        return CBO;
    }

    public void setCBO(int CBO) {
        this.CBO = CBO;
    }

    public int getRFC() {
        return RFC;
    }

    public void setRFC(int RFC) {
        this.RFC = RFC;
    }

    public int getLCOM() {
        return LCOM;
    }

    public void setLCOM(int LCOM) {
        this.LCOM = LCOM;
    }

    public int getCe() {
        return Ce;
    }

    public void setCe(int ce) {
        Ce = ce;
    }

    public int getNPM() {
        return NPM;
    }

    public void setNPM(int NPM) {
        this.NPM = NPM;
    }

    public int getCa() {
        return Ca;
    }

    public void setCa(int ca) {
        Ca = ca;
    }

    public Double getLCOM3() {
        return LCOM3;
    }

    public void setLCOM3(Double LCOM3) {
        this.LCOM3 = LCOM3;
    }

    public int getLOC() {
        return LOC;
    }

    public void setLOC(int LOC) {
        this.LOC = LOC;
    }

    public Double getDAM() {
        return DAM;
    }

    public void setDAM(Double DAM) {
        this.DAM = DAM;
    }

    public int getMOA() {
        return MOA;
    }

    public void setMOA(int MOA) {
        this.MOA = MOA;
    }

    public Double getMFA() {
        return MFA;
    }

    public void setMFA(Double MFA) {
        this.MFA = MFA;
    }

    public Double getCAM() {
        return CAM;
    }

    public void setCAM(Double CAM) {
        this.CAM = CAM;
    }

    public int getIC() {
        return IC;
    }

    public void setIC(int IC) {
        this.IC = IC;
    }

    public int getCBM() {
        return CBM;
    }

    public void setCBM(int CBM) {
        this.CBM = CBM;
    }

    public Double getAMC() {
        return AMC;
    }

    public void setAMC(Double AMC) {
        this.AMC = AMC;
    }


    }

    }

逻辑问题出在这段代码中

     public List<Metrics> readMetricFromCSV(String fileName) {

    List<Metrics> metricsss = new ArrayList<>();

    Path pathToFile = Paths.get(fileName);        // create an instance of BufferedReader
                                                  // using try with resource, Java 7 feature to close resources
    try (BufferedReader br = Files.newBufferedReader(pathToFile,
    StandardCharsets.US_ASCII)) {
    // read the first line from the text file
    String line = br.readLine();
    while (line != null && !line.isEmpty()) { // loop until all lines

         if (line.contains("~ ")) {
            continue;
          }
                                                    // are read
    String[] attributes = line.split(" "); // the file, using a  comma as the  delimiter first  18 values

    Metrics valueOfMetric = createMetric(attributes);          
    metricsss.add(valueOfMetric); // adding metric into ArrayList
    br.readLine();
    line = br.readLine();
        }

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

    return metricsss;
    }

【问题讨论】:

  • “逻辑问题在这段代码中” 告诉我们逻辑问题是什么,很难,对吧?真可惜。

标签: java arrays parsing csv text-files


【解决方案1】:

知道我会选择另一种方式。

try(BufferedReader br = new BufferedReader(new FileReader(file))) {
    for(String line; (line = br.readLine()) != null; ) {
       if(!line.contains("~")){
             String[] attributes = line.split(" ");
             Metrics valueOfMetric = createMetric(attributes);          
             metricsss.add(valueOfMetric); 
       }
    }
}

通常使用否定查找比使用肯定查找更容易/更好。通过使用 !Line 您基本上避免了不必要的 continue 代码(并不是说您不能使用它,但代码出错的地方更多)。然后在您使用的代码的末尾

br.readline()
line = br.readline()

这本身可能不会破坏您的代码,只是真的没有必要。

所以这段代码会读到文件末尾,避免空值,避免带“~”的行。

【讨论】:

  • 你应该解释你在这里做了什么来解决这个问题。
  • 似乎他想阅读所有不涉及“~”的行......这不仅解决了这个问题,而且还摆脱了很多糟糕的编码,包括“继续” , br.readline 和 line=br.readline 都是不必要的......一个简短/甜蜜/简洁/(应该)工作的答案......
  • 我的意思是——你的回答太短太神秘了。不要在评论中添加解释,您应该扩展您的答案,解释旧代码的问题是什么,以及您的新代码做了什么。这样,您的回答不仅对这个人有用,而且对碰巧有类似问题的其他人有用。
  • ahhhhh - 帮助...一秒钟的ol'教学方面:P
  • 你在修复“)”后再次尝试我的吗?
【解决方案2】:

使用univocity-parsersCsvParser。它支持行首的注释字符,并且可以轻松处理您的输入 CSV:

CsvParserSettings settings = new CsvParserSettings(); //many options here, check the tutorial

settings.getFormat().setComment('~');     

// creates a CSV parser
CsvParser parser = new CsvParser(settings);

// parses all rows in one go.
List<String[]> allRows = parser.parseAll(new FileReader(new File("/path/to/file.csv")));

【讨论】:

    猜你喜欢
    • 2020-07-06
    • 2019-01-09
    • 2022-06-14
    • 2017-10-19
    • 2014-03-09
    • 2010-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多