?
Solved

Implementing some methods in a csv reader class

Posted on 2005-04-02
48
Medium Priority
?
231 Views
Last Modified: 2013-11-23
Hello Experts,
Iam using the below code to read a csv file. Now i would like to implement some methods in this class .
0
Comment
Question by:vihar123
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 24
  • 24
48 Comments
 

Author Comment

by:vihar123
ID: 13689045
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.File;
import java.util.Vector;
import java.util.*;



public class New1 {
   
     private File file;
     private BufferedReader br;
       
     public New1(String filename) throws IOException {
         file = new File(filename);
         open();
     }
   
     private void open() throws IOException {
       br = new BufferedReader(new FileReader(file));
     }
     
     private static String[] Measuringpoints = {
         "Date", "Time", "",
         "E2-1N", "E2-2N", "E2-3N", "E2-4-1N", "E2-4-2", "E2-5-1",
         "E2-5-2N", "E2-6-1N", "E2-6-2N", "E2-1NT", "E2-2NT", "E2-3NT",
         "E2-4-1NT", "E2-4-2T", "E2-5-1T", "E2-5-2NT", "E2-6-1NT", "E2-6-2NT",
         "E2-1NTK", "E2-2NTK", "E2-3NTK", "E2-4-1NTK", "E2-4-2TK", "E2-5-1TK",
         "E2-5-2NTK", "E2-6-1NTK", "E2-6-2NTK"};
   
       
     private static String[] Units = {
         "", "", "",
         "bar", "bar", "bar", "bar", "bar", "bar",
         "bar", "bar", "bar", "°C", "°C", "°C",
         "°C", "°C", "°C", "°C", "°C", "°C",
         "bar", "bar", "bar", "bar", "bar", "bar",
         "bar", "bar", "bar"};
         
   
     public void Readline(){
       
        String str;
                           
          while ((str = br.readLine()) != null) {
             
          Measurement mst=new Measurement();
           String[] fields = str.split("\\s*?,\\s*?");
          mst.setDate(fields[0] + "," + fields[1]);
                   
          for(int i=3;i<fields.length;i++){
            mst.setMeasuringPoint(Measuringpoints[i]);
            mst.setUnit(Units[i]);
                       
          try
          {
           mst.setValue(Float.valueOf(fields[i]));
         
          }
          catch( NumberFormatException ex )
          {
           // do nothing...just skip this one
          }
 
         
         
           }// end of for
                     
          }// end of while
          br.close();
      } catch (IOException e) {  }
           
    }// end of Readline
     
    public static void main(String [] args)throws Exception {
       
     New1 nw1=new New1("exp.csv");
     nw1.Readline();
             
     }// end of main
   
} // end of class

0
 

Author Comment

by:vihar123
ID: 13689082
09.12.2000,20:00:00,A,2.4393,1.7338,0.76857,0.49934,0.21145,0.07567,-0.0213,-0.0607,-0.01101,7.8265,7.9302,8.1106,9.3818,9.9753,8.3042,8.1558,9.7239,8.9558,2.4254,1.7214,0.76584,0.491,0.20016,0.06087,-0.02317,-0.06668,-0.2408

is one of the row in my csv file


The methods that i would like to implement are
1)Here iam using some set methods like setdate(),setmeasuringpoints(),setvalues().Now i would like to store these as objects in a vector .
2)in my csv there are some rows with same date and same time , So i would like to store only one row , if there are some similar rows of the same date and time .
3)And methods to delete a column and a row
4)Here iam using string arrays for measuring points and units , Instead of this i would like to write some new class like property and use them in our new1 class.
0
 
LVL 8

Expert Comment

by:koppcha
ID: 13689543
>1)Here iam using some set methods like setdate(),setmeasuringpoints(),setvalues().Now i would like to store these as >objects in a vector
               You can keep the mst objects in a vector everytime you lop over the rows.

>2)in my csv there are some rows with same date and same time , So i would like to store only one row , if there are >some similar rows of the same date and time .
>3)And methods to delete a column and a row
         Before inserting you can loop over the vector and see the date attribute and decide if you have to add it to the vector or not.

>4)Here iam using string arrays for measuring points and units , Instead of this i would like to write some new class like >property and use them in our new1 class
         If you want to create a class then you have to again collect all the list of those objects and loop over to get the value for setMeasuringPoint().

   Are you looking for code?





0
Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

 

Author Comment

by:vihar123
ID: 13689649
yes , it would be nice if you give me the code
0
 
LVL 8

Expert Comment

by:koppcha
ID: 13694585
Hi sorry for the delayed response..
Once you start coding i would be able to help you out.
Let me know where you have doubts ?
0
 

Author Comment

by:vihar123
ID: 13698859
Hi ,
Regarding storing the objects in a Vector , Each measuring point represents a column of values.I would like to store the objects in that way.I should be able to get the values at that particular measuring object.
How can i achieve it ?

Thanks
0
 
LVL 8

Expert Comment

by:koppcha
ID: 13699278
In the object  what you can do is create two maps
1st Map with Integer as the key and value as the name of the column like this
1->Date
2->Time
3->E2-1N
4-> E2-2N
You build this map in the constructor of the class and write one more method which takes two arguments
first argument-->No of the filed
second argument --> value of the field
This method will take two parameters and create amap with first argument as the key and second argumetn as the value.

so what happens is
when you parse the first line of the file you will get them in string array .
you will pass those elements of the array with the field index so it will be like (1,fiels[0]) (2,field[1]).By the end of this it will populate the map with index as the key and field value as the value of the key

So after that you can use the two maps
1->Date
2->Time
3->E2-1N
4-> E2-2N
**********
1->09.12.2000
2->20:00:00
3->A
4->2.4393
*********
and get the corresponding values for the corresponding columns

Hope this gives you an idea


0
 

Author Comment

by:vihar123
ID: 13700393
Can you give me the code please ?
0
 
LVL 8

Expert Comment

by:koppcha
ID: 13700426
ok..I am at work right now..I will give me in about 5 hours.Is that OK ?
0
 

Author Comment

by:vihar123
ID: 13700548
ok , And please try to give me the code for my remaining questions also.
Thanks
0
 
LVL 8

Accepted Solution

by:
koppcha earned 2000 total points
ID: 13704280
Hi
  This program will run only on JAVA1.5 older version does not support the features i used.
Here i created two programs though it is not the entire code but definitely this can help you and you can go forward with that.
*******************Row Attribute**************************************************
//This class has the attributes as the parameters
package ClassProject;
import java.util.*;
public class RowAttribute
{
      Map<Integer,String> mapNames = new HashMap<Integer,String>();
      Map<Integer,String> mapValues = new HashMap<Integer,String>();
      //This is the constructor where you put all the attributes in a map
      public void RowAttribute() {
            mapNames.put(1,"Date");
            mapNames.put(2,"Time");
            mapNames.put(3,"");
            mapNames.put(5,"E2-1N");
            mapNames.put(6,"E2-2N");
            mapNames.put(7,"E2-3N");
            
      }
      //This is another map where you put all the values for the above mentioned attributes
      public void setAttributes(int i ,String value){
            mapValues.put(i,value);
      }
}
***********************************************************************************

This is the main program
package ClassProject;
import java.util.*;
import java.io.*;
public class fileParser
{
      public static void main(String[] args) {
      try{
      BufferedReader temp = new BufferedReader(new FileReader("data.txt"));
      String data = null;
      ArrayList listParameterObjects = new ArrayList();
   
      while((data = temp.readLine())!= null){
            RowAttribute rowAttribute = new RowAttribute();
            String[] fields = data.split("\\,");
            //Iterate through the whole attributes and populate them
            for(int i =0;i<fields.length;i++){
                  rowAttribute.setAttributes(i,fields[i]);
            }
            //Keep the object in the list so by the end you will have list of objects
            listParameterObjects.add(rowAttribute);
      }

      }
                  catch(Exception e) {
            System.out.println("File is not found" + e);
      }
            }
}
      
*********************************************************************************

try to understand this and you are all set to carry it on.In case you need any suggestions let me know







0
 

Author Comment

by:vihar123
ID: 13705300
Hi ,
Before adding the objects to the map , i have to apply some set methods like setdate,setvalues.setUnit ........
Here i have to change the date format to
private SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy,HH:mm:ss", Locale.GERMAN);
And the Values to Float format.
I have one class called new with set and get methods

mport java.util.Date;
import java.util.Locale;
import java.text.SimpleDateFormat;

public class New
{
   private Date date;
   private float value;
   private String unit;
   private String measuringPoint;
   private SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy,HH:mm:ss", Locale.GERMAN);

   public New()
  {
    this.date = null;
    this.value = 0.0F;
    this.unit = "";
    this.measuringPoint = null;
    }

  public Date getDate()
  {
    return this.date;
  }

  public void setDate(Date date)
  {
    this.date = date;
  }

  public float getValue()
  {
    return this.value;
  }

  public void setValue(float value)
  {
    this.value = value;
  }

  public String getUnit()
  {
    return this.unit;
  }

  public void setUnit(String unit)
  {
    this.unit = unit;
  }

  public String getMeasuringPoint()
  {
    return this.measuringPoint;
  }

  public void setMeasuringPoint(String measuringPoint)
  {
    this.measuringPoint = measuringPoint;
  }


And How to Read the Objects that are stored in the Map.

Thanks
0
 
LVL 8

Expert Comment

by:koppcha
ID: 13706448
In the case i mentioned i am placing the objects in the list in that case you have to iterate through the list and get the objects but if you have your objects in a MAP then you can access them by the uniques key value with which you would have populated the map ..using the key get the value which is the object.

Map
HashMap map1 = new HaspMap();
map1.put("name","koppcha");
map1.put("no","12345");
System.out.println("This is my name "+ map1.get("name"));
The above statement print This is my name koppcha

List
ArrayList list1 = new ArrayList();
Iterator listIterator = list1.iterator;
while (listItertor.hasNext()){
System.out.println("This is the element in the list " + listIterator.next());
}

Hope this helps
0
 
LVL 8

Expert Comment

by:koppcha
ID: 13706653
Your implementation which be easier if you follow my logic above.Its gonna be  hardly 30-40 lines code in the main program.
0
 

Author Comment

by:vihar123
ID: 13706920
Hi ,
Using above code to get the objects , the output is like

This is the element in the list  RowAttribute@82ba41
This is the element in the list  RowAttribute@923e30
.....
What does this represents ?
0
 
LVL 8

Expert Comment

by:koppcha
ID: 13706966
ok which one did you use can youpost the code you used exactly as it is
0
 

Author Comment

by:vihar123
ID: 13707138
The code that i used is

Iterator listIterator =listParameterObjects.iterator;
while (listItertor.hasNext()){
System.out.println("This is the element in the list " + listIterator.next());
}
0
 

Author Comment

by:vihar123
ID: 13707147
The code that i used is

Iterator listIterator =listParameterObjects.iterator();
while (listIterator.hasNext()){
System.out.println("This is the element in the list " + listIterator.next());
}
0
 
LVL 8

Expert Comment

by:koppcha
ID: 13707397
ok you can see the contents like this

Iterator listIterator =listParameterObjects.iterator();
while (listIterator.hasNext()){
RowAttribute row = rowAttribute(listIterator.next());
System.out.println("This is Date  " + row.getDate());
}

Before doing this you have to add the corresponding methods in the RowAttribute  class.
for example this is code for getDate
public String getDate() {
return mapValues.get(1);
}

0
 

Author Comment

by:vihar123
ID: 13707518
>> RowAttribute row = rowAttribute(listIterator.next());Error : can not find  rowAttribute method
how to implement rowAttribute() method
0
 
LVL 8

Expert Comment

by:koppcha
ID: 13707536
sorry it is a typo
it should be like this i am casting

RowAttribute row =(rowAttribute)listIterator.next();
0
 

Author Comment

by:vihar123
ID: 13707709
But here e we aren't using the setmethods that i told you before to change the formats like
private SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy,HH:mm:ss", Locale.GERMAN);
And the Values to Float format.
0
 
LVL 8

Expert Comment

by:koppcha
ID: 13707828
you have to do that in this method of RowAttribute.What you could do is if i=1 you know it is date so call setDate methos and return value and you keep that value in the map

here is the sample code
public void setAttributes(int i ,String value){
String keyvalue = null;      
if(i==1){
keyvalue = setDateFormat(value);
}
if(i==2){
keyValue = setTimeFormat(value);
}
If(i>3) {
keyValue = setValueFloatFormat(value);
}
       
mapValues.put(i,keyValue );
}
private Date setDateFormat(String value) {
//Change to date format
}


Hope This Helps
0
 

Author Comment

by:vihar123
ID: 13708172
the return type for my set methods is void , but here you are initializing keyvalue with set methods
0
 
LVL 8

Expert Comment

by:koppcha
ID: 13708294
Hmmmm.You can change  
1>Either change the name of the methods something else like getDate,getTime
if you are particular about your signature of the set methods then ok

declare all elements as private in the RowAttribute class
like
private Date date;
private Time time;
private  Float valueFoat;

and  in the set methods just set those elements like
private Date setDateFormat(String value) {
//after changing the format
date=value;
}

so your setAttributes method will look  like this
public void setAttributes(int i ,String value){
String keyvalue = null;      
if(i==1){
keyvalue = date;
}
if(i==2){
keyValue = time;
}
If(i>3) {
keyValue = valueFoat;
}
       
mapValues.put(i,keyValue );
}


Hope everything is clear



0
 

Author Comment

by:vihar123
ID: 13708520
Hi ,
in my csv there are some rows with same date and same time , So i would like to store only one row , if there are some similar rows of the same date and time
And methods to delete a column and a row
thanks
0
 
LVL 8

Expert Comment

by:koppcha
ID: 13708576
>if there are some similar rows of the same date and time
>And methods to delete a column and a row
         Can you give clear example for this?
0
 

Author Comment

by:vihar123
ID: 13708944
06.12.2000,12:00:00,A,2.4514,1.7406,0.77708,0.49914,0.21191,0.07578,-0.02234,-0.05221,-0.00998,7.8507,7.9658,8.1882,9.4646,10.11,8.3386,8.1882,9.7869,8.9768,2.4375,1.7282,0.77437,0.49084,0.20076,0.06102,-0.02421,-0.05816,-0.2303
06.12.2000,12:00:00,A,2.4514,1.7406,0.77708,0.49914,0.21191,0.07578,-0.02234,-0.05221,-0.00998,7.8507,7.9658,8.1882,9.4646,10.11,8.3386,8.1882,9.7869,8.9768,2.4375,1.7282,0.77437,0.49084,0.20076,0.06102,-0.02421,-0.05816,-0.2303

Above are the two rows in my csv with same date,time and values.

In such case instead of storing same data two times i would like to store only one time.
0
 
LVL 8

Expert Comment

by:koppcha
ID: 13709555
you have to write a method in the RowAttribue to return the main method
like this

public Map getMainMap() {
      return mapValues;
}

You have to compare this map in the main program with the map of the
existing object.

It goes like this
while((data = temp.readLine())!= null){
          RowAttribute rowAttribute = new RowAttribute();
          String[] fields = data.split("\\,");
          //Iterate through the whole attributes and populate them
          for(int i =0;i<fields.length;i++){
               rowAttribute.setAttributes(i,fields[i]);
          }
          //New changes come here
              Iterator listObjectIterator = listParameterObjects.iterator;
              while(listObjectIterator.hasNext()){
           RowAttribute tempRowAttribute=(RowAttribute)listObjectIterator.next();
           if(tempRowAttribute.equals(rowAttribute.getMainMap())){
                     System.out.println("The same row occured again");
               }
               else{
         listParameterObjects.add(rowAttribute);
               }
     }

HOPE THIS HELPS ALL THE BEST
0
 

Author Comment

by:vihar123
ID: 13710439
String keyvalue = null;      
if(i==1){
keyvalue = date;
}
if(i==2){
keyValue = time;
}
If(i>3) {
keyValue = valueFoat;
}
       
mapValues.put(i,keyValue );
}

>>keyvalue = date;here keyvalue is String and date is private Date date.........
same for time and value
0
 
LVL 8

Expert Comment

by:koppcha
ID: 13710574
ok it is better to store with their own object type
so do this

Date  tempDate = null;
Time tempTime = null;
Float tempValueFloat = null;      
if(i==1){
tempDate = date;
mapValues.put(i,tempDate );
}
if(i==2){
tempTime = time;
mapValues.put(i,tempTime );
}
If(i>3) {
tempValueFloat = valueFoat;
mapValues.put(i,tempValueFloat );

}
       

}


0
 
LVL 8

Expert Comment

by:koppcha
ID: 13710580
Are you a student? If so which univ?
0
 
LVL 8

Expert Comment

by:koppcha
ID: 13716008
Hope you are done with the above stuff
0
 

Author Comment

by:vihar123
ID: 13722158
No , iam still checking .
0
 

Author Comment

by:vihar123
ID: 13726554
Date  tempDate = null;
Time tempTime = null;
Float tempValueFloat = null;      
if(i==1){
tempDate = date;
mapValues.put(i,tempDate ); << Error like put method of (java.lang.Integer,java.lang.String ) can't be applied to (int,java.long.Date)
}
if(i==2){
tempTime = time;
mapValues.put(i,tempTime ); <<Error like put method of (java.lang.Integer,java.lang.String ) can't be  to put (int ,java.long.Date)
 

}
If(i>3) {
tempValueFloat = valueFoat;
mapValues.put(i,tempValueFloat );<<Error like put method of (java.lang.Integer,java.lang.String ) can't be applied to (int,java.long.Float)

}

Sorry to ask you again , but iam very confused wíth typecasting .
Thanks
0
 
LVL 8

Expert Comment

by:koppcha
ID: 13726661
No Problem
 In the RowAttribute we declared it like this
 Map<Integer,String> mapValues = new HashMap<Integer,String>();

Just change this to this and let me know if this issue is resolved

Map<Integer,Object> mapValues = new HashMap<Integer,Object>();

0
 

Author Comment

by:vihar123
ID: 13731670
Hi ,
Now iam getting errors in fileparser class

This is Date  null

File is not found java.util.ConcurrentModificationException
0
 
LVL 8

Expert Comment

by:koppcha
ID: 13731752
post the part of the code where you are parsing the file
0
 

Author Comment

by:vihar123
ID: 13731879
public static void main(String[] args) {
     try{
     BufferedReader temp = new BufferedReader(new FileReader("exp.csv"));
     String str=null;
     ArrayList list = new ArrayList();
       
     while((str = temp.readLine())!= null){
          RowAttribute rowAttribute = new RowAttribute();
          String[] fields = str.split("\\,");
          for(int i =0;i<fields.length;i++){
           rowAttribute.setAttributes(i,fields[i]);
          }
          list.add(rowAttribute);
       
          Iterator  listIterator = list.iterator();
          while (listIterator.hasNext()){
           
          RowAttribute row = (RowAttribute)listIterator.next();
          if(row.equals(rowAttribute.getMainMap())){
                  System.out.println("The same row occured again"); }
             else{ list.add(rowAttribute);   }


          System.out.println("This is Date  " + row.getDate());
             
          }
          } // while

          //System.out.println("This is the element in the list " + listIterator.next());}
       } // try
               catch(Exception e) {
          System.out.println("File is not found" + e);   }
       

     
   } // main
} // class
0
 
LVL 8

Expert Comment

by:koppcha
ID: 13732015
Keep the file in the same directory where the above main program is
0
 

Author Comment

by:vihar123
ID: 13735123
Hi, Its not a problem with the patrh of directory ,its throwing an exception called java.util.ConcurrentModificationException .

public class ConcurrentModificationException
extends RuntimeException

This exception may be thrown by methods that have detected concurrent modification of a backing object when such modification is not permissible

How to handle "java.util.ConcurrentModificationException " .?
0
 
LVL 8

Expert Comment

by:koppcha
ID: 13736947
This is someting that happens when two or more threads are updating a collection which wouldnt have happened in our case.Today evening i will try your whole code.Just post the entire code what you have written.
0
 

Author Comment

by:vihar123
ID: 13737324
ok,
 thanks
0
 

Author Comment

by:vihar123
ID: 13738363
The above one is the file parser class ,and now the rowaatribute class
New n=new New();
       Map<Integer,String> mapNames = new HashMap<Integer,String>();
     Map<Integer,Object> mapValues = new HashMap<Integer,Object>();

 
        public Object getDate() {
        return mapValues.get(1);
       }

     public void RowAttribute() {
          mapNames.put(1,"Date"); mapNames.put(2,"Time"); mapNames.put(3,"");mapNames.put(4,"E2-1N");
          mapNames.put(5,"E2-2N");mapNames.put(6,"E2-3N");mapNames.put(7,"E2-4-1N");mapNames.put(8,"E2-4-2");
          mapNames.put(9,"E2-5-1");mapNames.put(10,"E2-5-2N");mapNames.put(11,"E2-6-1N");
          mapNames.put(12,"E2-6-2N");mapNames.put(13,"E2-1NT");mapNames.put(14,"E2-2NT");
          mapNames.put(15,"E2-3NT");mapNames.put(16,"E2-4-1NT");mapNames.put(17,"E2-4-2T");
          mapNames.put(18,"E2-5-1T");mapNames.put(19,"E2-5-2NT");mapNames.put(20,"E2-6-1NT");
          mapNames.put(21,"E2-6-2NT");mapNames.put(22,"E2-1NTK");mapNames.put(23,"E2-2NTK");
          mapNames.put(24,"E2-3NTK");mapNames.put(25,"E2-4-1NTK");mapNames.put(26,"E2-4-2TK");
          mapNames.put(27,"E2-5-1TK");mapNames.put(28,"E2-5-2NTK");mapNames.put(29,"E2-6-1NTK");
          mapNames.put(30,"E2-6-2NTK");
         
     }
     public Map getMainMap() {
     return mapValues;
    }

     //This is another map where you put all the values for the above mentioned attributes
     public void setAttributes(int i ,String value){
         String keyvalue = null;  
         Date  tempDate = null;
         Float tempValueFloat = null;
         if(i==1&i==2){
         tempDate=n.setDate(value);
         mapValues.put(i,tempDate );

         }
         if(i>3) {
         tempValueFloat=n.setValue(Float.valueOf(value));
         mapValues.put(i,tempValueFloat );

        }
       
       
       }

         
}

And the New class is also available in the Above posts .

Thanks and waiting for your reply.
0
 
LVL 8

Expert Comment

by:koppcha
ID: 13761825
Sorry didn't get a chance to work on this.Will resolve this soon.Let me know when is the deadline
0
 

Author Comment

by:vihar123
ID: 13777338
Ok Thanks
But now iam doin this in a different way . Thanks a lot for your help.
0
 
LVL 8

Expert Comment

by:koppcha
ID: 13777457
Great..
Good Luck
0
 
LVL 8

Expert Comment

by:koppcha
ID: 13814663
Thanks for the grade.Hope you found a solution
0

Featured Post

Want to be a Web Developer? Get Certified Today!

Enroll in the Certified Web Development Professional course package to learn HTML, Javascript, and PHP. Build a solid foundation to work toward your dream job!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
The viewer will learn how to implement Singleton Design Pattern in Java.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
Suggested Courses
Course of the Month12 days, 21 hours left to enroll

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question