简体   繁体   中英

java check a given string in csv file

I have a csv file the format is like this:

在此处输入图片说明

I have a another csv file which is the same number of columns and rows.

在此处输入图片说明

I need to check if file 1 has same value (value[0]) as file 2 and if not copy value from file 2.

Below is the code I have written, but when checking, if file 1 first row value is not equal to the row, I need to go and check the next row of file 2 without exiting the if statement.

while ((line = br4.readLine()) != null){
      while ((line5 = br5.readLine()) != null){
             String[] values = line.split(",");
             String[] values5 = line5.split(",");
             fw5.append("0").append('\n');
             String comp2 = values[0];
             String comp1 =  values5[0];

             if (values5[0] == null ? values[0] == null : values5[0].equals(values[0]))
                    {
                    fw6.append(values[0]).append("mad men ").append('\n');
                    }                     
              else if ( values5[0] == null ? (values[0]) != null : !values5[0].equals(values[0])){
                        System.out.println("value is " +values5[0]);
                       fw6.append(values5[0]).append("mad women").append('\n');
                       fw6.flush();
                    } 
                      break; 
                    }       
                }

You are facing a typical newbie problem: insufficient abstractions.

You try to solve your whole problem in one method: instead create helpful abstractions. Like this:

  • first you create a class representing that row data. You might pass a string (content of one row) to the constructor. Then that class splits the string and puts all entries into meaningful named fields (instead of using an array named values which does not say anything).
  • then you add methods to that class to compare two instances of the class (could be the equals method or something you define on your own).
    • and while doing all of that you keep testing the code as you write.
  • then when you can parse that line of text and compare it as desired - then you add the code to read lines from your files. You read all lines, create objects and update them as required.
  • and finally you write code that writes updated objects back into file.

Long story short: slice your big problem into smaller ones and solve them one after the other.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM