File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Array expert's help needed Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Array expert Watch "Array expert New topic

Array expert's help needed

Rish Gupta

Joined: Sep 29, 2011
Posts: 29

As it is pretty obvious I get an Array Index out of bound exception.
Is there any way around this, I am trying to get the path of all the files in the root directory into an array of strings.
String[] filesFromDest = new String[500]; this declaration is lame too, is there any way I can keep the string length variable.
Any suggestions will be appreciated and Thanks in Advance.

Console Says:

C:\filesys\fileSys1\Copy (2)
C:\filesys\fileSys1\Copy (2)\Copy (2) (3)
C:\filesys\fileSys1\Copy (2)\Copy (2) (3)\doc - Copy (2) (3) 1 - Copy.txt
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 500
at com.rxBatch.Test.fetchFilesFromDirectory(
at com.rxBatch.Test.fetchFilesFromDirectory(
at com.rxBatch.Test.fetchFilesFromDirectory(
at com.rxBatch.Test.main(
Rish Gupta

Joined: Sep 29, 2011
Posts: 29
in case you dont want to read the entire code, all I am doing is making a recursive call to a method that checks if we are working on a file or directory. If it is a directory it calls the the method again and if it is a file it stores its path name at the end of a string which we will print at the end.
Matthew Brown

Joined: Apr 06, 2010
Posts: 4543

The simplest answer is to stop using an array and use a List instead (e.g. ArrayList). Then you can add new values as often as you like, and it will grow as necessary.
Rish Gupta

Joined: Sep 29, 2011
Posts: 29
what was i thinking.. 0.o
Harsha Smith
Ranch Hand

Joined: Jul 18, 2011
Posts: 287
Always prefer Arraylists to Arrays.

Reason....... Arrays are covariant and lists are invariant


class Fruit{}

class Apple extends Fruit{}

class Orange extends Fruit{}

Fruit [] fruits = new Apple[1];

fruits [0] = new Orange(); //compiles perfectly but throws ArrayStoreException when executed

ArrayList<Fruit> fruitList = new ArrayList<Apple>(); //won't compile(type mismatch)

ArrayList<? extends Fruit> fruitList = new ArrayList<Apple>(); compiles but useless as we can't add anything to this list except null

examples taken from the book....Thinking in Java (4th edition)

I agree. Here's the link:
subject: Array expert's help needed
It's not a secret anymore!