*
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Array expert Watch "Array expert New topic
Author

Array expert's help needed

Rish Gupta
Greenhorn

Joined: Sep 29, 2011
Posts: 28

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(Test.java:31)
at com.rxBatch.Test.fetchFilesFromDirectory(Test.java:27)
at com.rxBatch.Test.fetchFilesFromDirectory(Test.java:27)
at com.rxBatch.Test.main(Test.java:13)
Rish Gupta
Greenhorn

Joined: Sep 29, 2011
Posts: 28
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
Bartender

Joined: Apr 06, 2010
Posts: 4342
    
    7

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
Greenhorn

Joined: Sep 29, 2011
Posts: 28
ARRAY LIST
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

example:

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)





 
Consider Paul's rocket mass heater.
 
subject: Array expert's help needed
 
Similar Threads
looping on files ordered by file name
on File methods
Java directory
Merging byte arrays using SequenceInputStream
ArrayList does not print to terminal window after if statement inclusion, help?