user3930361
user3930361

Reputation: 181

Convert a File[ ] to String [ ]

Problem: Convert a File[ ] to String [ ]

File[] objectArray=getXMLFiles(new File("C:\\some-path"));
String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);

Exception:

Exception in thread "main" java.lang.ArrayStoreException
    at java.lang.System.arraycopy(Native Method)
    at java.util.Arrays.copyOf(Unknown Source)

I do understand this exception is coming because i am directly copying the file Object to String array.But can someone help me with converting my objectArray to stringArray.Please help me a easy way to convert this.

Requirement: I want that file array elements to be picked one by one so that 1 by 1 will get location of the file and will process in loop.Sample below.aAL and cAL is arraylist.

 for (int i = 0; i < 4; i++) {
     String fp=stringArray(i); //String array required to do this.
     String accountNum=aAL.get(i).toString();
     String custId=cAL.get(i).toString();
    Runnable worker = new XMLMultithreading(fp,anum,cid);
    executor.execute(worker);
    }

Thanks

Upvotes: 1

Views: 107

Answers (2)

Simone Gianni
Simone Gianni

Reputation: 11662

You can't cast a File to String, cause a File is not a String.

However File has a few methods (getName(), getAbsolutePath()) that return a String.

So you can do :

String[] stringArray = new String[objectArray.length];
for (int i = 0; i < objectArray.length; i++) stringArray[i] = objectArray[i].getAbsolutePath();

Upvotes: 1

Arno_Geismar
Arno_Geismar

Reputation: 2330

you could do this

File[] files =getXMLFiles(new File("C:\\some-path"));
fileArray = new String[files.length];
for (int i = 0; i < files.length; ++i){
fileArray[i] = files[i].getName();
}

Upvotes: 0

Related Questions