Add Files To File Array In Java

Active3 years, 6 months ago

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.

John McCarthyJohn McCarthy

5 Answers

File

Looks like you are right on. I've put together your code bit more cleanly.

NishanNishan
2,3184 gold badges19 silver badges35 bronze badges

More 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 - Vash
26.2k7 gold badges48 silver badges91 bronze badges

Add 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.

AmitAmit
ManojManoj
4,1497 gold badges48 silver badges77 bronze badges

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

Subhojit DasSubhojit Das

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.

File array in javaFiles

Let us compile and run the above program, this will produce the following result −

Add Files To File Array In Java File

java_io_file.htm