-1
try {
    rs = stmt.executeQuery("select firstname, middlename, lastname from users where  username = '" + var_1 + "'");
    if (rs == null || (!rs.next())) {
        record = var_1;
        FileInputStream file = new FileInputStream("C:/workspace/table_export.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(file));
        String line = null;
        while ((line = br.readLine()) != null) {
            String[] tokens = line.split("\\s+");
            if (tokens[0].equals(record)) {
                int size = tokens.length;
                for (int i = 0; i <= size; i++) {
                    fw.append(tokens[i]);
                    fw.append(',');
                }
                fw.append('\n');
            }
        }
    }
}

Hi all,

Am trying to query a database using a filter value retrieved from text file.

If the result set returns empty, i am searching for that filter value in the same text file and copying the whole line that contained the values to an array by splitting space.

Then i write the array to a csv file.

My text file has values like this

yzr200123 xxxx yyyy  
dd4534554 xydy frde

var_1=yzr200123, dd4534554

Note: This var_1 value does not exist in db, so i have to search for the value in text file and write the whole line to csv..

output.csv

yzr200123,xxxx,yyyy

dd4534554,xydy,frde

As one could see its writing to the csv file but i am getting the following exception,

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at simplejdbc.SimpleJDBC.getstaffid(SimpleJDBC.java:119)
at simplejdbc.SimpleJDBC.main(SimpleJDBC.java:64)

Is there a way we can avoid this exception by tuning the code. Any inputs would be appreciated.

Thanks in advance

BackSlash
  • 21,927
  • 22
  • 96
  • 136
navman
  • 75
  • 3
  • 8

1 Answers1

4
for(int i=0;i<=size;i++)

Is wrong. Since array indexes start from 0, you have to loop until i<size.

for(int i=0;i < size;i++) {
    fw.append(tokens[i]);
    fw.append(',');
}

Let's say that the array length is 4. Indexes are 0-based, so available indexes will be 0, 1, 2, 3. With your loop, you are trying to access indexes 0, 1, 2, 3, 4. The 5th element (which has index 4) doesn't exist, so it will throw an IndexOutOfBoundsException

BackSlash
  • 21,927
  • 22
  • 96
  • 136