How is this done in Java? I wish to create an array of fileNames to output in a program, the files will be the ones in my home directory.
The java.io.File.list() returns the array of files and directories in the directory defined by this abstract path name. The method returns null, if the abstract pathname does not denote a directory. The method returns null, if the abstract pathname does not denote a directory.
So far I have :
Is this all I need ?
And then, to print out those files, can I just do :
Thanks very much.
5 Answers
Looks like you are right on. I've put together your code bit more cleanly.
NishanNishanMore or less yes, but you need to check that file is a file not a directory of course if you need only files names.
Damian Leszczyński - VashDamian Leszczyński - VashAdd Files To File Array In Java
Yes that's how we get the list of file from local directory. Please note that the listFiles() will also include directories. So if you are interested only in files then you got to check isFile() on each file. If you are interested to get selective file user FileFilter.
This is simplest way by which you can build array of files present in your home directory. And using the loop, you can get the name of all files very easily. Here is the code:
Java Read File Into Array
Not the answer you're looking for? Browse other questions tagged javaarraysfile or ask your own question.
- Java.io package classes
- Java.io package extras
- Java.io package Useful Resources
- Selected Reading
Description
The java.io.File.list() returns the array of files and directories in the directory defined by this abstract path name. The method returns null, if the abstract pathname does not denote a directory.
Declaration
Following is the declaration for java.io.File.list() method −
Parameters
NA
Return Value
The method returns array of files and directories in the directory denoted by this abstract pathname.
Exception
Byte Array To File Java
SecurityException − If a security manager exists and its SecurityManager.checkRead(java.lang.String) method denies read access to the file
Example
Add Files To File Array In Java Download
The following example shows the usage of java.io.File.list() method.
Let us compile and run the above program, this will produce the following result −