Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Setting null value to a setter method

802235Oct 1 2010 — edited Oct 1 2010
I have searched answer for this dowbt in many places.But I could not get. Please help me

I want to read a .csv file.

I passed each of the row to an arraylist and used .split() to seperate fields of each row.I am passing the split method results to a Sting[].

StringTokenizer is not useful as, if the row has blank values,the .hasMoreTokens condition becomes false and it skips that row goes to next.

So I used the split method. It takes the blank values. The point is if the field of last column of any row is blank, it is not taking it as "" but takes it as null.

I want to set the each field in array to setter methods.if The field of last column is null, it not setting to the setter method and ArrayIndexOutofBoundException occurs.

Can anyone please tell me how set null value to a setter method to avoid that exception.


This is my code
public class CSVExample{

EcmSoBulkVO ecmVO = new EcmSoBulkVO();  //bean class 

public static void main(String args[]) {
		String file = "D:/trialCSVs/ECMSO.csv";  
          
 //name of the .csv file. Please treat the col as col 1,2,3,4,5,6

		CSVExample csv = new CSVExample();
		csv.getRec(file);
	}

	public Object getRec(String file) {
		String[] fields=new String[6];
		try {
			BufferedReader br = new BufferedReader(new FileReader(file));
			ArrayList line = new ArrayList();			
			int lineNumber = 0;
						
			while ((file = br.readLine()) != null) {
				if (lineNumber != 0) {
					line.add(file);
					fields=file.split(",");
					
                    for(int count=0;count<fields.length;count++){
                    	System.out.println(" "+fields[count]);
                    	if(fields[count]==null){
                    		fields[count]="";
                    	}
                    }
                    ecmVO.setApNo(fields[0]);
	    ecmVO.setEcmNo(fields[1]);
	    ecmVO.setEcmDesc(fields[2]);
	    ecmVO.setSoNo(fields[3]);
	    ecmVO.setSoDesc(fields[4]);
	    ecmVO.setAccNo(fields[5]);  // exception occurs here, this is the last field in the .csv file

          }
return ecmVO;
}
Only six setter methods are there in the bean class. If the last setter method is null, this problem occurs

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at com.CSVExample.getRec(CSVExample.java:51)

Edited by: Kaj on 2010-okt-01 08:40
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Oct 29 2010
Added on Oct 1 2010
6 comments
3,785 views