How to list the file names in a directory in Java?

Lot of times we need to list or search a particular file in a directory in java. Java I/O API provides the methods to this operation.

We can use following methods to list the file names in a directory :

listFiles

This method returns the files in a directory with a format of abstract path names.
If the file calling this method is not a directory then this method returns null. We can also filter the files which returns using FileFilter and FileNameFilter passing as an argument to this method.

isDirectory

This particular method is important because it checks whether specified file is directory or not. This method returns true if the file with the path exists and it is a directory.

isFile

This method returns true if specified file is of type file.
Now we can use these methods to list the files or filenames in a directory.

import java.io.File;

public class ListFileDemo {

  public static void main(String[] args) {

    File directory = new File("C:/");
    File[] filelist = directory.listFiles(); //Listing the files in directory

    for ( int i = 0; i < filelist.length; i++) {
      if ( filelist[i].isFile() ) { // Checking for file 

        System.out.println( "File " + filelist[i].getName() );
      
      } else if ( filelist[i].isDirectory() ) { // Checking for directory

        System.out.println( "Directory " + filelist[i].getName() );
      
      }
    }
  }

}

For listing the files we can also set the FileFilters, if we want to retrieve only the directories then we can use following filter.

FileFilter dirFilter = new FileFilter() {
    public boolean accept( File demoFile )  {
        return demoFile.isDirectory(); // Accepts only directories.
    }
};
files = dir.listFiles( dirFilter );

Similar to above filter mechanism, we can also use FilenameFilter which is used to have filter based on file names. Lets see the example below in which we are filtering the files only starting with character 'a'.

FilenameFilter fileFilter = new FilenameFilter() {
    public boolean accept(File directory, String filename) {
        return filename.startsWith("a");
    }
};
files = directory.list( fileFilter ); // List the files starting with character 'a' .

Java I/O Streams Tutorial – Part 1

We all know stream is a sequence of data, input and output streams represent the input sources and the output destination. These sources can include memory arrays, programs or devices. The data which we send also categorized into the objects, simple bytes, primitive data types, characters or multimedia types.

Java Development Kit provides APIs for reading and writing streams of data. We can find them in java.io package. For reading the data Java opens a stream to a data source such as a file or remote socket and on other side for writing it again opens stream and write serially.

Now lets see the types of streams :

Byte Stream :

Bytestreams deals with byte data type. Programs use byte streams for input and output of 8 bit bytes. The classes which support bytestream are InputStream and OutputStream.

Character Stream:

As the name suggest character streams deals with characters having Unicode conventions. Character streams are supported by java.io.Reader and java.io.Writer and their subclasses. Character streams are less complicated than byte streams and more powerful which directly translates the format to and from using the local character set. Character streams have lot of advantages such as they can handle any character in Unicode character set. Character streams are not dependent on specific character set for encoding , they quickly adapt the local character set so it becomes very easy to internationalize. Also the buffering techniques also makes them efficient than byte streams , so unless we need to input or output any binary data such as image or sound files we can use character streams.

Buffered Stream :

In the above two streams, reading and writing request being taken care at underlying OS which makes them somehow less efficient. To decrease the overhead , JDK gives the buffered stream APIs .
The memory area which is used for reading and writing operation is called as buffer. Program can convert unbuffered stream to buffered stream by passing unbuffered stream to the constructor of buffered stream class. To wrap unbuffered byte stream to the buffered byte stream classes used are BufferedInputStream and BufferedOutputStream and for character stream buffering BufferedReader and BufferedWriter classes are used.

How to copy one directory to another directory in java?

Below is the code snippet of method to copy one directory to another directory. The method accepts two arguments one is source directory and another is target directory. This method copies the subdirectories and subfiles recursively as shown below.

public static void copyDirectory(File sourceDir , File targetDir)  throws IOException {
        
        if (sourceDir.isDirectory()) {
            if (!targetDir.exists()) {
                targetDir.mkdir();
            }
            
            String[] childFiles = sourceDir.list();
            for (int i=0; i 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
        }
    }

How to read contents of File in Java?

We can read the contents of a file using two techniques, first is reading contents using DataInputStream and another is
BufferedReader.

Reading contents using DataInputStream:

DataInputStream makes easier to read integer, float, double data and other primitive data types without needing to interpret if the read data should be an integer or double etc.

        DataInputStream in = null;
        BufferedReader br = null;
         try{
            

            FileInputStream fileInputStream = new FileInputStream("C:\\test7.txt" );
            // Getting the object of DataInputStream
            in = new DataInputStream( fileInputStream );
            br = new BufferedReader(new InputStreamReader(in));
            String strLine;
            
            while ((strLine = br.readLine()) != null)   {
            
              System.out.println (strLine);
            }
            
    }catch (Exception e){//Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }finally{
            
            if( in != null){
                try{
                    
                    in.close();
                }catch(IOException es){
            
                }
            }
            if( br != null){
                try{
                    
                    br.close();
                }catch(IOException es){
            
                }
            }
        }

Reading the file contents using BufferedReader :

BufferedReader is used to read text from a character-input stream, it buffers characters to provide for the efficient reading of characters, Strings and Arrays. As seen in example below we use FileReader object to pass to the BufferedReader and calling readLine() method on BufferedReader object to read the line.

BufferedReader in = null;
        try {
            in = new BufferedReader( new FileReader(  "C:\\test7.txt"  ));
            String line = null;
            while ( (line = in.readLine()) != null) {
                writer.println(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                if (in != null)
                    in.close();
            } catch (Exception exp) {
            }
        }

How to write into a File in Java?

We can write contents into a file using two methods , using BufferedWriter and FileOutputStream , lets see how we can write the contents using these methods :

Writing a file using BufferedWriter :
BufferedWriter write text to a character-output stream, it buffers characters to provide efficient writing of single characters, Strings and Arrays. We can also pass buffer size if not provided default size is used which is considerably large to perform most of the writing operations.
When writing new line character a new method newLine() is provided, as we can see in below example we are creating a FileWriter object and passing it to the BufferedWriter object and we use write method to write the contents, after writing the contents we are closing the BufferedWriter.

BufferedWriter out = null;
        try{
            FileWriter fWriter = new FileWriter("C:\\test1.txt"); //Creates new file if already not exists
            out = new BufferedWriter(fWriter);
            out.write("This is a test");
            out.newLine(); // Writes new line
            
        }catch(IOException es){
            
        }finally{
            
            if( out != null){
                try{
                    out.close();
                }catch(IOException es){
            
                }
            }
        }

Writing using FileOutputStream:

FileOutputStream is a stream used to write the contents into a File. But when we write string object we need to convert it to byte and then send it to the write method.

FileOutputStream fopStream = null;
        try{
              File testFile = new File( "C:\\test7.txt" );
              fopStream = new FileOutputStream(testFile);

              if(!testFile.exists()){
                  testFile.createNewFile();
              }
              String str="This is a test using FileOutputStream";
              fopStream.write(str.getBytes());
             

            
        }catch(IOException es){
            
        }finally{
            
            if( fopStream != null){
                try{
                    
                    fopStream.flush();
                    fopStream.close();             //Close the output stream
                }catch(IOException es){
            
                }
            }
        }