| Author |
Array expert's help needed
|
Rish Gupta
Greenhorn
Joined: Sep 29, 2011
Posts: 14
|
|
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: 14
|
|
|
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: 3786
|
|
|
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: 14
|
|
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)
|
 |
 |
|
|
subject: Array expert's help needed
|
|
|