views:

131

answers:

4

The title is basically all there is too it. I have an array of file objects...

File[] myFiles = myDirectory.listFiles();

And I want to convert it to an array of strings. (String[])

+3  A: 

Assuming you want the file names, just use

String[] myFileNames = myDirectory.list();

It does the same thing as listFiles but instead of returning File objects it returns Strings[] of the file/directory names.

TofuBeer
+4  A: 

Assuming that it's the file paths you want, just create a String array of the same size, and iterate through the arrays getting the file paths and putting them in the String array:

String[] myStrings = new String[myFiles.length()];
for( int i = 0; i < myFiles.length(); i++ )
{
    myStrings[i] = myFiles[i].getPath();
}

Same for file names or whatever, just call the method for the string you want. I haven't written Java for a while, so the syntax might be slightly off, but that should give you the idea.

Travis Christian
Sorry I didn't mention the file paths is what I want. This worked though!! Thanks!
Jack Love
A: 

If you're looking to get the contents of the files as strings (which could be a very bad idea if you have enormous files), you can use the snippet to read the File to a string: http://snippets.dzone.com/posts/show/1335

Then combine that with Travis' answer to see how you would iterate over the files, call the function, and save the contents of the file to a string.

I82Much
+1  A: 

FWIW here's a Scala way to do it:

val myStrings = myFiles.map(_.getPath)
Eric Grindt