Apache Commons IO - Quick Guide



Apache Commons IO - Overview

Apache Commons IO library provides various utility classes for common operations for File IO covering wide range of use cases. It helps avoid writing boilerplate code.

Classes

Apache Commons IO library provides classes for following categories −

Utility classes

These classes which are under org.apache.commons.io package, provides file and string comparison. Following are some of the examples.

  • IOUtils − Provides utility methods for reading, writing and copying files. The methods work with InputStream, OutputStream, Reader and Writer.

  • FilenameUtils − Provides method to work with file names without using File Object. It works on different operating systems in similar way.

  • FileUtils − Provides method to manipulates files like moving, opening, checking existence, reading of file etc. These methods use File Object.

  • IOCase − Provides method for string manipulation and comparison.

  • FileSystemUtils − Provides method to get the free space on a disk drive.

  • LineIterator − Provides a flexible way to work with a line-based file.

Filter classes

Filter classes which are under org.apache.commons.io.filefilter package, provides methods to filter files based on logical criteria instead of string based tedious comparisons. Following are some of the examples.

  • NameFileFilter − Filters file-names for a name.

  • WildcardFileFilter − Filters files using the supplied wildcards.

  • SuffixFileFilter − Filters files based on suffix. This is used in retrieving all the files of a particular type.

  • PrefixFileFilter − Filters files based on prefix.

  • OrFileFilter − Provides conditional OR logic across a list of file filters. Returns true, if any filters in the list return true. Otherwise, it returns false.

  • AndFileFilter − Provides conditional and logic across a list of file filters. Returns false if any filters in the list return false. Otherwise, it returns true.

File Monitor classes

File monitor classes which are under org.apache.commons.io.monitor package, provides control to track changes in a specific file or folder and allows to do action accordingly on the changes. Following are some of the examples.

  • FileEntry − Provides the state of a file or directory. File attributes at a point in time.

  • FileAlterationObserver − Represents the state of files below a root directory, checks the file system and notifies listeners of create, change or delete events.

  • FileAlterationMonitor − Represents a thread that spawns a monitoring thread triggering any registered FileAlterationObserver at a specified interval.

Comparator classes

File monitor classes under org.apache.commons.io.comparator package allow to compare and sort files and directories easily.

  • NameFileComparator − Compare the names of two files.

  • SizeFileComparator − Compare the size of two files.

  • LastModifiedFileComparator − Compare the last modified dates of two files.

Stream classes

There are multiple implementation of InputStream under org.apache.commons.io.input package and of OutputStream under org.apache.commons.io.output package, to do useful tasks on streams. Following are some of the examples.

  • NullOutputStream − Absorbs all data sent with any error.

  • TeeOutputStream − Sends output to two streams.

  • ByteArrayOutputStream − Faster version of JDK class.

  • CountingOutputStream − Counts the number of bytes passed through the stream.

  • ProxyOutputStream − Changes the calls to proxy stream.

  • LockableFileWriter − A FileWriter to create lock files and allow simple cross thread file lock handling.

Apache Commons IO - Environment Setup

This chapter will guide you on how to prepare a development environment to start your work with Apache Commons IO. It will also teach you how to set up JDK on your machine before you set up Apache Commons IO −

Setup Java Development Kit (JDK)

You can download the latest version of SDK from Oracle's Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively.

If you are running Windows and have installed the JDK in C:\jdk-19, you would have to put the following line in your C:\autoexec.bat file.

set PATH=C:\jdk-19;%PATH% 
set JAVA_HOME=C:\jdk-19

Alternatively, on Windows NT/2000/XP, you will have to right-click on My Computer, select Properties → Advanced → Environment Variables. Then, you will have to update the PATH value and click the OK button.

On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk-19 and you use the C shell, you will have to put the following into your .cshrc file.

setenv PATH /usr/local/jdk-19/bin:$PATH 
setenv JAVA_HOME /usr/local/jdk-19

Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, you will have to compile and run a simple program to confirm that the IDE knows where you have installed Java. Otherwise, you will have to carry out a proper setup as given in the document of the IDE.

Popular Java Editors

To write your Java programs, you need a text editor. There are many sophisticated IDEs available in the market. But for now, you can consider one of the following −

  • Notepad − On Windows machine, you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad.

  • Netbeans − It is a Java IDE that is open-source and free, which can be downloaded from www.netbeans.org/index.html.

  • Eclipse − It is also a Java IDE developed by the eclipse open-source community and can be downloaded from www.eclipse.org.

Download Common IO Archive

Download the latest version of Apache Common IO jar file from commons-io-2.20.0-bin.zip. At the time of writing this tutorial, we have downloaded commons-io-2.20.0-bin.zip and copied it into C:\>Apache folder.

OS Archive name
Windows commons-io-2.20.0-bin.zip
Linux commons-io-2.20.0-bin.tar.gz
Mac commons-io-2.20.0-bin.tar.gz

Set Apache Common IO Environment

Set the APACHE_HOME environment variable to point to the base directory location where Apache jar is stored on your machine. Assuming, we've extracted commons-io-2.20.0-bin.zip in Apache folder on various Operating Systems as follows.

OS Output
Windows Set the environment variable APACHE_HOME to C:\Apache
Linux export APACHE_HOME=/usr/local/Apache
Mac export APACHE_HOME=/Library/Apache

Set CLASSPATH Variable

Set the CLASSPATH environment variable to point to the Common IO jar location. Assuming, you have stored commons-io-2.20.0-bin.zip in Apache folder on various Operating Systems as follows.

OS Output
Windows Set the environment variable CLASSPATH to %CLASSPATH%;%APACHE_HOME%\commons-io-2.20.0.jar;.
Linux export CLASSPATH=$CLASSPATH:$APACHE_HOME/commons-io-2.20.0.jar:.
Mac export CLASSPATH=$CLASSPATH:$APACHE_HOME/commons-io-2.20.0.jar:.

Apache Commons IO - IOUtils Class

Overview

IOUtils class provide utility methods for reading, writing and copying files. The methods work with InputStream, OutputStream, Reader and Writer.

Class Declaration

Following is the declaration for org.apache.commons.io.IOUtils Class −

public class IOUtils
   extends Object

Features of IOUtils

The features of IOUtils are given below −

  • Provides static utility methods for input/output operations.

  • toXXX() − reads data from a stream.

  • write() − write data to a stream.

  • copy() − copy all data to a stream to another stream.

  • contentEquals − compare the contents of two streams.

Here is the input file we need to parse −

input.txt

Welcome to TutorialsPoint. 
Simply Easy Learning.

Example - Convert Stream to String using IOUtils

CommonsIoTester.java

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.IOUtils;

public class CommonsIoTester {
   public static void main(String[] args) throws IOException {
      try(InputStream in = new FileInputStream("input.txt")) {
         String data = IOUtils.toString( in , "UTF-8");
		 System.out.println(data);
      }
   }
}

Output

It will print the following result −

Welcome to TutorialsPoint. 
Simply Easy Learning.

Example - Transfer data using IOUtils

CommonsIoTester.java

package com.tutorialspoint;

import java.io.FileWriter;
import java.io.IOException;

import org.apache.commons.io.IOUtils;

public class CommonsIoTester {
   public static void main(String[] args) {
      try (FileInputStream fis = new FileInputStream("input.txt");
         FileOutputStream fos = new FileOutputStream("output.txt")) {
         IOUtils.copy(fis, fos);
         System.out.println("Data transferred successfully.");
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

Output

It will print the following result −

Data transferred successfully.

You can check the content of output.txt file created in current directory as −

Welcome to TutorialsPoint. 
Simply Easy Learning.

Example - Writing String to Stream using IOUtils

CommonsIoTester.java

package com.tutorialspoint;

import java.io.FileWriter;
import java.io.IOException;

import org.apache.commons.io.IOUtils;

public class CommonsIoTester {
   public static void main(String[] args) throws IOException {
      try (FileWriter writer = new FileWriter("output.txt")) {
         IOUtils.write("Welcome to Tutorialspoint.", writer);
         IOUtils.write(System.lineSeparator(), writer);
         IOUtils.write("Simple Easy Learning.", writer);
         System.out.println("Content written to file.");
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

Output

It will print the following result −

Content written to file.

You can check the content of output.txt file created in current directory as −

Welcome to Tutorialspoint.
Simple Easy Learning.

Apache Commons IO - FileUtils Class

Overview

FileUtils class provides method to manipulates files like moving, opening, checking existence, reading of file etc. These methods use File Object.

Class Declaration

Following is the declaration for org.apache.commons.io.FileUtils Class −

public class FileUtils
   extends Object

Features of FileUtils

The features of FileUtils are stated below −

  • Methods to write to a file.
  • Methods to read from a file.
  • Methods to make a directory including parent directories.
  • Methods to copy files and directories.
  • Methods to delete files and directories.
  • Methods to convert to and from a URL.
  • Methods to list files and directories by filter and extension.
  • Methods to compare file content.
  • Methods to file last changed date.
  • Methods to calculating a checksum.

Here is the input file we're using in our examples −

input.txt

Welcome to TutorialsPoint. 
Simply Easy Learning.

Example - Writing to a Temporary directory using FileUtils

CommonsIoTester.java

package com.tutorialspoint;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

public class CommonsIoTester {
   public static void main(String[] args) throws IOException {
      //get the file object
      File file = FileUtils.getFile("input.txt");

      //get the temp directory
      File tmpDir = FileUtils.getTempDirectory();

      System.out.println(tmpDir.getName());

      //copy file to temp directory
      FileUtils.copyFileToDirectory(file, tmpDir);
	  
	  System.out.println("File written successfully.");
   }
}

Output

It will print the following result −

Temp
File written successfully.

Example - Reading from Temporary directory using FileUtils

CommonsIoTester.java

package com.tutorialspoint;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;

import org.apache.commons.io.FileUtils;

public class CommonsIoTester {
   public static void main(String[] args) throws IOException {
      //get the temp directory
      File tmpDir = FileUtils.getTempDirectory();
	      
      //create a new file
      File newTempFile = FileUtils.getFile(tmpDir, "input.txt");

      //get the content
      String data = FileUtils.readFileToString(newTempFile, Charset.defaultCharset());

      //print the content
      System.out.println(data);
   }
}

Output

It will print the following result −

Welcome to TutorialsPoint. 
Simply Easy Learning.

Example - Copy File using FileUtils

CommonsIoTester.java

package com.tutorialspoint;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

public class CommonsIoTester {
   public static void main(String[] args) throws IOException {
      //get the file objects
      File sourceFile = new File("input.txt");
	  File destinationFile = new File("output.txt");
	  
	  // copy file
      FileUtils.copyFile(sourceFile, destinationFile);
      System.out.println("input.txt copied to output.txt");
   }
}

Output

It will print the following result −

input.txt copied to output.txt

You can check the content of output.txt file created in current directory as −

Welcome to TutorialsPoint. 
Simply Easy Learning.

Apache Commons IO - FilenameUtils Class

Overview

FilenameUtils class provides methods to work with file names without using File Object. It works on different operating systems in similar way. This class solves problems when moving from a Windows based development machine to a Unix based production machine.

Class Declaration

Following is the declaration for org.apache.commons.io.FilenameUtils Class −

public class FilenameUtils
   extends Object

Features of FilenameUtils

This class defines six components within a filename. Consider an example location as C:\dev\project\file.txt. Then the components are −

  • Prefix - C:\
  • Relative Path - dev\project\
  • Absolute path - C:\dev\project\
  • Name - file.txt
  • Base name - file
  • Extension - txt

To identify a directory, add a separator to file name.

Example - Getting Path details using FilenameUtils Class

CommonsIoTester.java

package com.tutorialspoint;

import java.io.IOException;
import org.apache.commons.io.FilenameUtils;

public class CommonsIoTester {
   public static void main(String[] args) throws IOException {
      String path = "C:\\dev\\project\\file.txt";
      System.out.println("Full Path: " +FilenameUtils.getFullPath(path));
      System.out.println("Relative Path: " +FilenameUtils.getPath(path));
      System.out.println("Prefix: " +FilenameUtils.getPrefix(path));
   }
}

Output

It will print the following result −

Full Path: C:\dev\project\
Relative Path: dev\project\
Prefix: C:\

Example - Getting File details using FilenameUtils Class

CommonsIoTester.java

package com.tutorialspoint;

import java.io.IOException;
import org.apache.commons.io.FilenameUtils;

public class CommonsIoTester {
   public static void main(String[] args) throws IOException {
      String path = "C:\\dev\\project\\file.txt";
      System.out.println("Extension: " + FilenameUtils.getExtension(path));
      System.out.println("Base: " + FilenameUtils.getBaseName(path));
      System.out.println("Name: " + FilenameUtils.getName(path));
   }
}

Output

It will print the following result −

Extension: txt
Base: file
Name: file.txt

Example - Getting Normalized Path using FilenameUtils Class

CommonsIoTester.java

package com.tutorialspoint;

import java.io.IOException;
import org.apache.commons.io.FilenameUtils;

public class CommonsIoTester {
   public static void main(String[] args) throws IOException {
      String filename = "C:/commons/io/../lang/project.xml";
      System.out.println("Normalized Path: " + FilenameUtils.normalize(filename));
   }
}

Output

It will print the following result −

Normalized Path: C:\commons\lang\project.xml

Apache Commons IO - FileSystemUtils Class

Overview

FileSystemUtils class provides method to get the free space on a disk drive.

Class Declaration

Following is the declaration for org.apache.commons.io.FileSystemUtils Class −

public class FileSystemUtils
   extends Object

Example - Getting Free Space of a drive in Bytes

CommonsIoTester.java

package com.tutorialspoint;

import java.io.IOException;

import org.apache.commons.io.FileSystemUtils;

public class CommonsIoTester {
   public static void main(String[] args) throws IOException {
      System.out.println("Free Space " + FileSystemUtils.freeSpace("C:/") + " Bytes");
   }
}

Output

It will print the following result −

Free Space 186157182976 Bytes

Example - Getting Free Space of a drive in KiloBytes

CommonsIoTester.java

package com.tutorialspoint;

import java.io.IOException;

import org.apache.commons.io.FileSystemUtils;

public class CommonsIoTester {
   public static void main(String[] args) throws IOException {
      System.out.println("Free Space " + FileSystemUtils.freeSpaceKb("C:/") + " KB");
   }
}

Output

It will print the following result −

Free Space 181794512 KB

Example - Getting Free Space of a drive in KiloBytes with timeout

CommonsIoTester.java

package com.tutorialspoint;

import java.io.IOException;

import org.apache.commons.io.FileSystemUtils;

public class CommonsIoTester {
   public static void main(String[] args) throws IOException {
      System.out.println("Free Space " + FileSystemUtils.freeSpaceKb("C:/",1000) + " KB");
   }
}

Output

It will print the following result −

Free Space 181794512 KB

Apache Commons IO - IOCase Enum

Overview

IOCase is an Enumeration of IO case sensitivity. Different Operating systems have different rules for case-sensitivity for file names. For example, Windows is case-insensitive for file naming while Unix is case-sensitive. IOCase captures that difference, provides an enumeration to control how filename comparisons should be performed. It also provides methods to use the enumeration to perform comparisons.

Enum Declaration

Following is the declaration for org.apache.commons.io.IOCase Enum −

public enum IOCase
   extends Enum<IOCase> implements Serializable

Example - Case Sensitive Check on a String

CommonsIoTester.java

package com.tutorialspoint;

import java.io.IOException;
import org.apache.commons.io.IOCase;

public class CommonsIoTester {
   public static void main(String[] args) throws IOException {
      String text = "WELCOME TO TUTORIALSPOINT. SIMPLY EASY LEARNING.";
      System.out.println("Ends with Learning (case sensitive): " + IOCase.SENSITIVE.checkEndsWith(text, "Learning."));
   }
}

Output

It will print the following result −

Ends with Learning (case sensitive): false

Example - Case Insensitive Check on a String

CommonsIoTester.java

package com.tutorialspoint;

import java.io.IOException;
import org.apache.commons.io.IOCase;

public class CommonsIoTester {
   public static void main(String[] args) throws IOException {
      String text = "WELCOME TO TUTORIALSPOINT. SIMPLY EASY LEARNING.";
      System.out.println("Ends with Learning (case insensitive): " + IOCase.INSENSITIVE.checkEndsWith(text, "Learning."));
   }
}

Output

It will print the following result −

Ends with Learning (case insensitive): true

Example - Case Sensitive Equality Check on Strings

CommonsIoTester.java

package com.tutorialspoint;

import java.io.IOException;
import org.apache.commons.io.IOCase;

public class CommonsIoTester {
   public static void main(String[] args) throws IOException {
      String text = "Welcome to TutorialsPoint. Simply Easy Learning.";
      String text1 = "WELCOME TO TUTORIALSPOINT. SIMPLY EASY LEARNING.";
      System.out.println("Equality Check (case sensitive): " + IOCase.SENSITIVE.checkEquals(text, text1));
      System.out.println("Equality Check (case insensitive): " + IOCase.INSENSITIVE.checkEquals(text, text1));
   }
}

Output

It will print the following result −

Equality Check (case sensitive): false
Equality Check (case insensitive): true

Apache Commons IO - LineIterator Class

Overview

LineIterator class provides a flexible way to work with a line-based file.

Class Declaration

Following is the declaration for org.apache.commons.io.LineIterator Class −

public class LineIterator
   extends Object implements Iterator<String>, Closeable

Usage of LineIterator

Get LineIterator using FileUtils.

try(LineIterator lineIterator = FileUtils.lineIterator(file)) {
...
}

Check if line exists using lineIterator.hasNext() method

while(lineIterator.hasNext()) {
...
}

Get the line contents using LineIterator.next() method

String lineContents = lineIterator.next()

Here is the input file we need to parse −

input.txt

Welcome to TutorialsPoint. Simply Easy Learning.
Learn web technologies,
prepare exams,
code online,
all at one place.

Example - Print each line of file using LineIterator class

CommonsIoTester.java

package com.tutorialspoint;

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;

public class CommonsIoTester {
   public static void main(String[] args) throws IOException {
      //get the file object
      File file = FileUtils.getFile("input.txt");
      try(LineIterator lineIterator = FileUtils.lineIterator(file)) {
         System.out.println("Contents of input.txt");
         while(lineIterator.hasNext()) {
            System.out.println(lineIterator.next());
         }
      }
   }
}

Output

It will print the following result −

Contents of input.txt
Welcome to TutorialsPoint. Simply Easy Learning.
Learn web technologies,
prepare exams,
code online,
all at one place.

Apache Commons IO - NameFileFilter Class

Overview

NameFileFilter class in Commons IO filters the file-names for a name.

Class Declaration

Following is the declaration for org.apache.commons.io.filefilter.NameFileFilter Class :

public class NameFileFilter
   extends AbstractFileFilter implements Serializable

Here is the input file we need to parse −

input.txt

Welcome to TutorialsPoint. Simply Easy Learning.

Example - Printing all files in current directory.

CommonsIoTester.java

package com.tutorialspoint;

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.IOCase;
import org.apache.commons.io.filefilter.NameFileFilter;

public class CommonsIoTester {
   public static void main(String[] args) throws IOException {
      //get the current directory
      File currentDirectory = new File(".");
      //get names of all files and directory in current directory
      String[] files = currentDirectory.list();
      System.out.println("All files and Folders.\n");
      for( int i = 0; i < files.length; i++ ) {
         System.out.println(files[i]);
      }
   }
}

Output

It will print the following result −

All files and Folders.

.classpath
.project
.settings
bin
input.txt
output.txt
src

Example - Filtering a file by name as Case Insensitive

CommonsIoTester.java

package com.tutorialspoint;

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.IOCase;
import org.apache.commons.io.filefilter.NameFileFilter;

public class CommonsIoTester {
   public static void main(String[] args) throws IOException {
      //get the current directory
      File currentDirectory = new File(".");
      System.out.println("\nFile with name input.txt\n");
      String[] acceptedNames = {"input", "input.txt"};
      String[] filesNames = currentDirectory.list( new NameFileFilter(acceptedNames, IOCase.INSENSITIVE) );
      for( int i = 0; i < filesNames.length; i++ ) {
         System.out.println(filesNames[i]);
      }
   }
}

Output

It will print the following result −

File with name input.txt

input.txt

Example - Filtering a file by name as Case Sensitive

CommonsIoTester.java

package com.tutorialspoint;

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.IOCase;
import org.apache.commons.io.filefilter.NameFileFilter;

public class CommonsIoTester {
   public static void main(String[] args) throws IOException {
      //get the current directory
      File currentDirectory = new File(".");
	  System.out.println("\nFile with name input.txt\n");
      String[] acceptedNames = {"input", "input.txt"};
      String[] filesNames = currentDirectory.list( new NameFileFilter(acceptedNames, IOCase.SENSITIVE) );
      for( int i = 0; i < filesNames.length; i++ ) {
         System.out.println(filesNames[i]);
      }
   }
}

Output

It will print the following result −

File with name input.txt

input.txt

Apache Commons IO - WildcardFileFilter Class

Overview

WildcardFileFilter class in Commons IO filters the files using the supplied wildcards.

Class Declaration

Following is the declaration for org.apache.commons.io.filefilter.WildcardFileFilter Class −

public class WildcardFileFilter
   extends AbstractFileFilter implements Serializable

Here is the input file we need to parse −

input.txt

Welcome to TutorialsPoint. Simply Easy Learning.

Example - Filtering a file names ending with t.

CommonsIoTester.java

package com.tutorialspoint;

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.filefilter.WildcardFileFilter;

public class CommonsIoTester {
   public static void main(String[] args) throws IOException {
      //get the current directory
      File currentDirectory = new File(".");
      System.out.println("\nFile name ending with t.\n");
      WildcardFileFilter filter = WildcardFileFilter.builder().setWildcards("*t").get();
   
      String[] filesNames = currentDirectory.list(filter);
      for( int i = 0; i < filesNames.length; i++ ) {
        System.out.println(filesNames[i]);
      }
   }
}

Output

It will print the following result −

File name ending with t.

.project
input.txt
output.txt

Example - Filtering a file names starting with i.

CommonsIoTester.java

package com.tutorialspoint;

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.filefilter.WildcardFileFilter;

public class CommonsIoTester {
   public static void main(String[] args) throws IOException {
      //get the current directory
      File currentDirectory = new File(".");

      System.out.println("\nFile name starting with i.\n");
      WildcardFileFilter filter = WildcardFileFilter.builder().setWildcards("i*").get();
   
      String[] filesNames = currentDirectory.list(filter);

      for( int i = 0; i < filesNames.length; i++ ) {
        System.out.println(filesNames[i]);
      }
   }
}

Output

It will print the following result −

File name starting with i.

input.txt

Apache Commons IO - SuffixFileFilter Class

Overview

SuffixFileFilter class filters the files which are based on suffix. This is used in retrieving all the files of a particular type.

Class Declaration

Following is the declaration for org.apache.commons.io.filefilter.SuffixFileFilter Class −

public class SuffixFileFilter 
   extends AbstractFileFilter implements Serializable

Here is the input file we need to parse −

input.txt

Welcome to TutorialsPoint. Simply Easy Learning.

Example - Filtering files with .txt extension.

CommonsIoTester.java

package com.tutorialspoint;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.filefilter.SuffixFileFilter;

public class CommonsIoTester {
   public static void main(String[] args) throws IOException {
      //get the current directory
      File currentDirectory = new File(".");
     
      String[] filesNames = currentDirectory.list( new SuffixFileFilter("txt"));
      for( int i = 0; i < filesNames.length; i++ ) {
         System.out.println(filesNames[i]);
      }
   }
}

Output

It will print the following result −

input.txt
output.txt

Example - Filtering files ending with t.

CommonsIoTester.java

package com.tutorialspoint;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.filefilter.SuffixFileFilter;

public class CommonsIoTester {
   public static void main(String[] args) throws IOException {
      //get the current directory
      File currentDirectory = new File(".");
     
      String[] filesNames = currentDirectory.list( new SuffixFileFilter("t"));
      for( int i = 0; i < filesNames.length; i++ ) {
         System.out.println(filesNames[i]);
      }
   }
}

Output

It will print the following result −

.project
input.txt
output.txt

Apache Commons IO - PrefixFileFilter Class

Overview

PrefixFileFilter class filters the files which are based on prefix.

Class Declaration

Following is the declaration for org.apache.commons.io.filefilter.PrefixFileFilter Class −

public class PrefixFileFilter 
   extends AbstractFileFilter implements Serializable

Here is the input file we need to parse −

input.txt

Welcome to TutorialsPoint. Simply Easy Learning.

Example - Filtering files starting with in.

CommonsIoTester.java

package com.tutorialspoint;

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.filefilter.PrefixFileFilter;

public class CommonsIoTester {
   public static void main(String[] args) {
   
      //get the current directory
      File currentDirectory = new File(".");
	  	  
      System.out.println("File starting with in");
      String[] filesNames = currentDirectory.list( new PrefixFileFilter("in") );
      for( int i = 0; i < filesNames.length; i++ ) {
         System.out.println(filesNames[i]);
      }
   }
}

Output

It will print the following result −

File starting with in
input.txt

Example - Filtering files starting with out.

CommonsIoTester.java

package com.tutorialspoint;

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.filefilter.PrefixFileFilter;

public class CommonsIoTester {
   public static void main(String[] args) {
      //get the current directory
      File currentDirectory = new File(".");

      System.out.println("File starting with out");
      String[] filesNames = currentDirectory.list( new PrefixFileFilter("out") );
      for( int i = 0; i < filesNames.length; i++ ) {
         System.out.println(filesNames[i]);
      }
   }
}

Output

It will print the following result −

File starting with out
output.txt

Apache Commons IO - OrFileFilter Class

Overview

OrFileFilter class provides conditional OR logic across a list of file filters. It returns true, if any filters in the list return true. Otherwise, it returns false.

Class Declaration

Following is the declaration for org.apache.commons.io.filefilter.OrFileFilter Class −

public class OrFileFilter 
   extends AbstractFileFilter implements ConditionalFileFilter, Serializable

Here is the input file we need to parse −

input.txt

Welcome to TutorialsPoint. Simply Easy Learning.

Example - Filtering files starting with . Or ending with t.

CommonsIoTester.java

package com.tutorialspoint;

import java.io.File;

import org.apache.commons.io.filefilter.OrFileFilter;
import org.apache.commons.io.filefilter.PrefixFileFilter;
import org.apache.commons.io.filefilter.WildcardFileFilter;

public class CommonsIoTester {
   public static void main(String[] args) {
      //get the current directory
      File currentDirectory = new File(".");
      PrefixFileFilter prefixFilter = new PrefixFileFilter(".");
      WildcardFileFilter wildCardfilter = WildcardFileFilter.builder().setWildcards("*t").get();
      OrFileFilter andFileFilter = new OrFileFilter(prefixFilter, wildCardfilter);

      String[] filesNames = currentDirectory.list( orFileFilter );
      for( int i = 0; i < filesNames.length; i++ ) {
         System.out.println(filesNames[i]);
      }
   }
}

Output

It will print the following result −

.classpath
.project
.settings
input.txt
output.txt

Example - Filtering files ending with txt Or starting with i.

CommonsIoTester.java

package com.tutorialspoint;

import java.io.File;

import org.apache.commons.io.filefilter.OrFileFilter;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.apache.commons.io.filefilter.WildcardFileFilter;

public class CommonsIoTester {
   public static void main(String[] args) {
      //get the current directory
      File currentDirectory = new File(".");
      SuffixFileFilter suffixFilter = new SuffixFileFilter("txt");
      WildcardFileFilter wildCardfilter = WildcardFileFilter.builder().setWildcards("i*").get();
      OrFileFilter orFileFilter = new OrFileFilter(suffixFilter, wildCardfilter);

      String[] filesNames = currentDirectory.list( orFileFilter );
      for( int i = 0; i < filesNames.length; i++ ) {
         System.out.println(filesNames[i]);
      }
   }
}

Output

It will print the following result −

input.txt
output.txt

Apache Commons IO - AndFileFilter Class

Overview

AndFileFilter class provides conditional AND logic across a list of file filters. It returns true, if all filters in the list return true. Otherwise, it returns false.

Class Declaration

Following is the declaration for org.apache.commons.io.filefilter.AndFileFilter Class −

public class AndFileFilter 
   extends AbstractFileFilter implements ConditionalFileFilter, Serializable

Here is the input file we need to parse −

input.txt

Welcome to TutorialsPoint. Simply Easy Learning.

Example - Filtering files starting with . And ending with t.

CommonsIoTester.java

package com.tutorialspoint;

import java.io.File;

import org.apache.commons.io.filefilter.AndFileFilter;
import org.apache.commons.io.filefilter.PrefixFileFilter;
import org.apache.commons.io.filefilter.WildcardFileFilter;

public class CommonsIoTester {
   public static void main(String[] args) {
      //get the current directory
      File currentDirectory = new File(".");
      PrefixFileFilter prefixFilter = new PrefixFileFilter(".");
      WildcardFileFilter wildCardfilter = WildcardFileFilter.builder().setWildcards("*t").get();
      AndFileFilter andFileFilter = new AndFileFilter(prefixFilter, wildCardfilter);

      String[] filesNames = currentDirectory.list( andFileFilter );
      for( int i = 0; i < filesNames.length; i++ ) {
         System.out.println(filesNames[i]);
      }
   }
}

Output

It will print the following result −

.project

Example - Filtering files ending with txt And starting with i.

CommonsIoTester.java

package com.tutorialspoint;

import java.io.File;

import org.apache.commons.io.filefilter.AndFileFilter;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.apache.commons.io.filefilter.WildcardFileFilter;

public class CommonsIoTester {
   public static void main(String[] args) {
      //get the current directory
      File currentDirectory = new File(".");
      SuffixFileFilter suffixFilter = new SuffixFileFilter("txt");
      WildcardFileFilter wildCardfilter = WildcardFileFilter.builder().setWildcards("i*").get();
      AndFileFilter orFileFilter = new AndFileFilter(suffixFilter, wildCardfilter);

      String[] filesNames = currentDirectory.list( andFileFilter );
      for( int i = 0; i < filesNames.length; i++ ) {
         System.out.println(filesNames[i]);
      }
   }
}

Output

It will print the following result −

input.txt
output.txt

Apache Commons IO - FileEntry Class

Overview

FileEntry class provides the state of a file or directory. File attributes at a point in time.

Class Declaration

Following is the declaration for org.apache.commons.io.monitor.FileEntry Class −

public class FileEntry
   extends Object implements Serializable

Features of FileEntry

FileEntry class object provides the following file attributes at a point in time.

  • getName() − file name.

  • exists() − checks if file exists or not.

  • isDirectory() − checks if file is a directory.

  • lastModified() − gives last modified date time.

  • listFiles() − gives content of directory.

Here is the input file we need to parse −

Welcome to TutorialsPoint. Simply Easy Learning.

Example - Get/Set Existing File Check

CommonsIoTester.java

package com.tutorialspoint;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.monitor.FileEntry;

public class CommonsIoTester {
   public static void main(String[] args) {
      //get the file object
      File file = FileUtils.getFile("input.txt");
      FileEntry fileEntry = new FileEntry(file);
      fileEntry.setExists(true);
      System.out.println("File Exists: " + fileEntry.isExists());
   }
}

Output

It will print the following result −

File Exists: true

Example - Get File Attributes

CommonsIoTester.java

package com.tutorialspoint;

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.monitor.FileEntry;

public class CommonsIoTester {
   public static void main(String[] args) {
      //get the file object
      File file = FileUtils.getFile("input.txt");
      FileEntry fileEntry = new FileEntry(file);
      System.out.println("Monitored File: " + fileEntry.getFile());
      System.out.println("File name: " + fileEntry.getName());
   }
}

Output

It will print the following result −

Monitored File: input.txt
File name: input.txt

Example - Get/Set directory status of a File

CommonsIoTester.java

package com.tutorialspoint;

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.monitor.FileEntry;

public class CommonsIoTester {
   public static void main(String[] args) {
      //get the file object
      File file = FileUtils.getFile("input.txt");
      FileEntry fileEntry = new FileEntry(file);
      fileEntry.setDirectory(true);
      System.out.println("Is Directory: " + fileEntry.isDirectory());
   }
}

Output

It will print the following result −

Is Directory: false

Apache Commons IO - FileAlterationObserver Class

Overview

FileAlterationObserver class represents the state of files below a root directory, checks the filesystem and notifies listeners of create, change or delete events.

Class Declaration

Following is the declaration for org.apache.commons.io.monitor.FileAlterationObserver Class −

public class FileAlterationObserver
   extends Object implements Serializable

Here is the input file we need to parse −

input.txt

Welcome to TutorialsPoint. Simply Easy Learning.

Example - Nofiying Creation of a Directory and File.

CommonsIoTester.java

package com.tutorialspoint;

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileDeleteStrategy;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;

public class CommonsIoTester {
   public static void main(String[] args) {
      //get the file object
      File inputFile = FileUtils.getFile("input.txt");
      String absolutePath = inputFile.getAbsolutePath();
      String parent = absolutePath.substring(0,absolutePath.indexOf("input.txt"));
      File parentDirectory = FileUtils.getFile(parent);
      FileAlterationObserver observer = FileAlterationObserver.builder().setFile(parentDirectory).get();
      observer.addListener(new FileAlterationListenerAdaptor() {
         @Override
         public void onDirectoryCreate(File file) {
            System.out.println("Folder created: " + file.getName());
         }        
         @Override
         public void onFileCreate(File file) {
            System.out.println("File created: " + file.getName());
         }
      });
      //create a monitor to check changes after every 500 ms
      FileAlterationMonitor monitor = new FileAlterationMonitor(500, observer);
      try {
          monitor.start();
         //create a new directory
         File newFolder = new File("test");
         File newFile = new File("test1");
         newFolder.mkdirs();
         Thread.sleep(1000);
         newFile.createNewFile();
         Thread.sleep(1000);
         monitor.stop(10000);
      } catch(IOException e) {
         System.out.println(e.getMessage());
      } catch(InterruptedException e) {
         System.out.println(e.getMessage());
      } catch (Exception e) {
         System.out.println(e.getMessage());
      }
   }
}

Output

It will print the following result −

Folder created: test
File created: test1

Example - Nofiying Deletion of a Directory and File.

CommonsIoTester.java

package com.tutorialspoint;

import java.io.File;

import org.apache.commons.io.FileDeleteStrategy;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;

public class CommonsIoTester {
   public static void main(String[] args) throws Exception {
      //get the file object
      File inputFile = FileUtils.getFile("input.txt");
      String absolutePath = inputFile.getAbsolutePath();
      String parent = absolutePath.substring(0,absolutePath.indexOf("input.txt"));
      File parentDirectory = FileUtils.getFile(parent);
      FileAlterationObserver observer = FileAlterationObserver.builder().setFile(parentDirectory).get();
      observer.addListener(new FileAlterationListenerAdaptor() {
         @Override
         public void onDirectoryDelete(File file) {
            System.out.println("Folder deleted: " + file.getName());
         }
         @Override
         public void onFileDelete(File file) {
            System.out.println("File deleted: " + file.getName());
         }
      });
      //create a monitor to check changes after every 500 ms
      FileAlterationMonitor monitor = new FileAlterationMonitor(500, observer);
      monitor.start();
      //create a new directory
      File newFolder = new File("test");
      File newFile = new File("test1");
      newFolder.mkdirs();
      Thread.sleep(1000);
      newFile.createNewFile();
      FileDeleteStrategy.NORMAL.delete(newFolder);
      Thread.sleep(1000);
      FileDeleteStrategy.NORMAL.delete(newFile);
      Thread.sleep(1000);
      monitor.stop(10000);
   }
}

Output

It will print the following result −

Folder deleted: test
File deleted: test1

Apache Commons IO - FileAlterationMonitor Class

Overview

FileAlterationMonitor class represents a thread that spawns a monitoring thread triggering any registered FileAlterationObserver at a specified interval.

Class Declaration

Following is the declaration for org.apache.commons.io.monitor.FileAlterationMonitor Class −

public class FileAlterationMonitor
   extends Object implements Runnable

Here is the input file we need to parse −

input.txt

Welcome to TutorialsPoint. Simply Easy Learning.

Example - Nofiying Creation of a Directory and File.

CommonsIoTester.java

package com.tutorialspoint;

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileDeleteStrategy;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;

public class CommonsIoTester {
   public static void main(String[] args) {
      //get the file object
      File inputFile = FileUtils.getFile("input.txt");
      String absolutePath = inputFile.getAbsolutePath();
      String parent = absolutePath.substring(0,absolutePath.indexOf("input.txt"));
      File parentDirectory = FileUtils.getFile(parent);
      FileAlterationObserver observer = FileAlterationObserver.builder().setFile(parentDirectory).get();
      observer.addListener(new FileAlterationListenerAdaptor() {
         @Override
         public void onDirectoryCreate(File file) {
            System.out.println("Folder created: " + file.getName());
         }        
         @Override
         public void onFileCreate(File file) {
            System.out.println("File created: " + file.getName());
         }
      });
      //create a monitor to check changes after every 500 ms
      FileAlterationMonitor monitor = new FileAlterationMonitor(500, observer);
      try {
          monitor.start();
         //create a new directory
         File newFolder = new File("test");
         File newFile = new File("test1");
         newFolder.mkdirs();
         Thread.sleep(1000);
         newFile.createNewFile();
         Thread.sleep(1000);
         monitor.stop(10000);
      } catch(IOException e) {
         System.out.println(e.getMessage());
      } catch(InterruptedException e) {
         System.out.println(e.getMessage());
      } catch (Exception e) {
         System.out.println(e.getMessage());
      }
   }
}

Output

It will print the following result −

Folder created: test
File created: test1

Example - Nofiying Deletion of a Directory and File.

CommonsIoTester.java

package com.tutorialspoint;

import java.io.File;

import org.apache.commons.io.FileDeleteStrategy;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;

public class CommonsIoTester {
   public static void main(String[] args) throws Exception {
      //get the file object
      File inputFile = FileUtils.getFile("input.txt");
      String absolutePath = inputFile.getAbsolutePath();
      String parent = absolutePath.substring(0,absolutePath.indexOf("input.txt"));
      File parentDirectory = FileUtils.getFile(parent);
      FileAlterationObserver observer = FileAlterationObserver.builder().setFile(parentDirectory).get();
      observer.addListener(new FileAlterationListenerAdaptor() {
         @Override
         public void onDirectoryDelete(File file) {
            System.out.println("Folder deleted: " + file.getName());
         }
         @Override
         public void onFileDelete(File file) {
            System.out.println("File deleted: " + file.getName());
         }
      });
      //create a monitor to check changes after every 500 ms
      FileAlterationMonitor monitor = new FileAlterationMonitor(500, observer);
      monitor.start();
      //create a new directory
      File newFolder = new File("test");
      File newFile = new File("test1");
      newFolder.mkdirs();
      Thread.sleep(1000);
      newFile.createNewFile();
      FileDeleteStrategy.NORMAL.delete(newFolder);
      Thread.sleep(1000);
      FileDeleteStrategy.NORMAL.delete(newFile);
      Thread.sleep(1000);
      monitor.stop(10000);
   }
}

Output

It will print the following result −

Folder deleted: test
File deleted: test1

Apache Commons IO - NameFileComparator Class

Overview

NameFileComparator class compares the names of two files. It can be used to sort the lists or arrays of files, using their name, either in a case-sensitive, case-insensitive or system dependent case sensitive way.

Class Declaration

Following is the declaration for org.apache.commons.io.comparator.NameFileComparator Class −

public class NameFileComparator
   extends Object implements Serializapackage com.tutorialspoint;

Example - Sorting all files of current Directory.

CommonsIoTester.java

package com.tutorialspoint;

import java.io.File;

import org.apache.commons.io.IOCase;
import org.apache.commons.io.comparator.NameFileComparator;

public class CommonsIoTester {
   public static void main(String[] args) throws Exception {
      //get the current directory
      File currentDirectory = new File(".");
      NameFileComparator comparator = new
      NameFileComparator(IOCase.SENSITIVE);
      File[] sortedFiles = comparator.sort(currentDirectory.listFiles());
      System.out.println("Sorted By Name: ");
      for(File file:sortedFiles) {
         System.out.println(file.getName());
      }  
   }
}

Output

It will print the following result −

Sorted By Name: 
.classpath
.project
.settings
bin
input.txt
output.txt
src

Example - Sorting filtered files of current Directory.

CommonsIoTester.java

package com.tutorialspoint;

import java.io.File;
import java.io.FileFilter;

import org.apache.commons.io.IOCase;
import org.apache.commons.io.comparator.NameFileComparator;
import org.apache.commons.io.filefilter.FileFileFilter;

public class CommonsIoTester {
   public static void main(String[] args) throws Exception {
      //get the current directory
      File currentDirectory = new File(".");
      NameFileComparator comparator = new
      NameFileComparator(IOCase.SENSITIVE);
      File[] sortedFiles = comparator.sort(currentDirectory.listFiles((FileFilter)FileFileFilter.FILE));
      System.out.println("Sorted By Name: ");
      for(File file:sortedFiles) {
         System.out.println(file.getName());
      }  
   }
}

Output

It will print the following result −

Sorted By Name: 
.classpath
.project
input.txt
output.txt

Apache Commons IO - SizeFileComparator Class

Overview

SizeFileComparator class compare the sizes of two files/directory. It can be used to sort the lists or arrays of files using their size or directories, based on their number of children.

Class Declaration

Following is the declaration for org.apache.commons.io.comparator.SizeFileComparator Class −

public class SizeFileComparator
   extends Object implements Serializable

Example - Sorting all files of current Directory.

CommonsIoTester.java

package com.tutorialspoint;

import java.io.File;
import org.apache.commons.io.comparator.SizeFileComparator;

public class CommonsIoTester {
   public static void main(String[] args) throws Exception {
      //get the current directory
      File currentDirectory = new File(".");
      SizeFileComparator comparator = new SizeFileComparator();
      File[] sortedFiles = comparator.sort(currentDirectory.listFiles());
      System.out.println("Sorted By Size: ");
      for(File file:sortedFiles) {
         System.out.println(file.getName());
      }  
   }
}

Output

It will print the following result −

Sorted By Size: 
.settings
bin
src
output.txt
input.txt
.project
.classpath

Example - Sorting filtered files of current Directory.

CommonsIoTester.java

package com.tutorialspoint;

import java.io.File;
import java.io.FileFilter;

import org.apache.commons.io.IOCase;
import org.apache.commons.io.comparator.SizeFileComparator;
import org.apache.commons.io.filefilter.FileFileFilter;

public class CommonsIoTester {
   public static void main(String[] args) throws Exception {
      //get the current directory
      File currentDirectory = new File(".");
      SizeFileComparator comparator = new SizeFileComparator();
      File[] sortedFiles = comparator.sort(currentDirectory.listFiles((FileFilter)FileFileFilter.FILE));
      System.out.println("Sorted By Size: ");
      for(File file:sortedFiles) {
         System.out.println(file.getName());
      }  
   }
}

Output

It will print the following result −

Sorted By Size: 
output.txt
input.txt
.project
.classpath

Apache Commons IO - LastModifiedFileComparator Class

Overview

LastModifiedFileComparator class compares the last modified dates of two files/directory. It can be used to sort the lists or arrays of files/directories using their last modified dates.

Class Declaration

Following is the declaration for org.apache.commons.io.comparator.LastModifiedFileComparator Class −

public class LastModifiedFileComparator
   extends Object implements Serializable

Example - Sorting all files of current Directory.

CommonsIoTester.java

package com.tutorialspoint;

import java.io.File;
import org.apache.commons.io.comparator.LastModifiedFileComparator;

public class CommonsIoTester {
   public static void main(String[] args) throws Exception {
      //get the current directory
      File currentDirectory = new File(".");
      LastModifiedFileComparator comparator = new LastModifiedFileComparator();
      File[] sortedFiles = comparator.sort(currentDirectory.listFiles());
      System.out.println("Sorted By Modified Date: ");
      for(File file:sortedFiles) {
         System.out.println(file.getName());
      }  
   }
}

Output

It will print the following result −

Sorted By Modified Date: 
.project
.settings
src
.classpath
bin
output.txt
input.txt

Example - Sorting filtered files of current Directory.

CommonsIoTester.java

package com.tutorialspoint;

import java.io.File;
import java.io.FileFilter;

import org.apache.commons.io.IOCase;
import org.apache.commons.io.comparator.LastModifiedFileComparator;
import org.apache.commons.io.filefilter.FileFileFilter;

public class CommonsIoTester {
   public static void main(String[] args) throws Exception {
      //get the current directory
      File currentDirectory = new File(".");
      LastModifiedFileComparator comparator = new LastModifiedFileComparator();
      File[] sortedFiles = comparator.sort(currentDirectory.listFiles((FileFilter)FileFileFilter.FILE));
      System.out.println("Sorted By Modified Date: ");
      for(File file:sortedFiles) {
         System.out.println(file.getName());
      }  
   }
}

Output

It will print the following result −

Sorted By Modified Date: 
.project
.classpath
output.txt
input.txt

Apache Commons IO - TeeInputStream Class

Overview

TeeInputStream class is an InputStream proxy that transparently writes a copy of all bytes which are read from the proxy stream to a given OutputStream. The proxy input stream is closed, when the close() method on this proxy is called. It can be used to operate two streams collectively at a time.

Class Declaration

Following is the declaration for org.apache.commons.io.input.TeeInputStream Class −

public class TeeInputStream
   extends ProxyInputStream

Steps of Using TeeInputStream

Step 1: Create a TeeOutputStream for two outputstreams

// create two output streams
ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream();
ByteArrayOutputStream outputStream2 = new ByteArrayOutputStream();
TeeOutputStream teeOutputStream = new TeeOutputStream(outputStream1, outputStream2);

Step 2: Create a TeeInputStream for TeeOutputStream

// create an input stream
ByteArrayInputStream inputStream = new ByteArrayInputStream("data".getBytes("US-ASCII"));
// create teeInputStream using inputStream, teeOutputStream and closeBranch flag as true
// if closeBranch is true, outputstream is automatically closed when teeInputstream is closed.
TeeInputStream teeInputStream = new TeeInputStream(inputStream, teeOutputStream, true);

Step 3: Read Data using TeeInputStream

teeInputStream.read(new byte["data".length()]);

Step 4: Verify data in output streams

System.out.println("Output stream 1: " + outputStream1.toString());
System.out.println("Output stream 2: " + outputStream2.toString());

Step 5: Close the stream.

//teeIn.close() closes teeIn and teeOut which in turn closes the out1 and out2.
teeInputStream.close();

Example - Usage of TeeInputStream.

CommonsIoTester.java

package com.tutorialspoint;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.apache.commons.io.input.TeeInputStream;
import org.apache.commons.io.output.TeeOutputStream;

public class CommonsIoTester {
   private static final String SAMPLE = "Welcome to TutorialsPoint. Simply Easy Learning.";
   public static void main(String[] args) {
      try {
         usingTeeInputStream();
      }catch(IOException e) {
         System.out.println(e.getMessage());
      }
   }
   public static void usingTeeInputStream() throws IOException {
      TeeInputStream teeInputStream = null;
      TeeOutputStream teeOutputStream = null;
      try {
         ByteArrayInputStream inputStream = new
         ByteArrayInputStream(SAMPLE.getBytes("US-ASCII"));
         ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream();
         ByteArrayOutputStream outputStream2 = new ByteArrayOutputStream();
         teeOutputStream = new TeeOutputStream(outputStream1, outputStream2);
         teeInputStream = new TeeInputStream(inputStream, teeOutputStream, true);
         teeInputStream.read(new byte[SAMPLE.length()]);
         System.out.println("Output stream 1: " + outputStream1.toString());
         System.out.println("Output stream 2: " + outputStream2.toString());
      }catch (IOException e) {
         System.out.println(e.getMessage());
      } finally {
         //teeIn.close() closes teeIn and teeOut which in turn closes the out1 and out2.
         try {
            teeInputStream.close();
         } catch (IOException e) {
            System.out.println(e.getMessage());
         }
      }
   }
}

Output

It will print the following result −

Output stream 1: Welcome to TutorialsPoint. Simply Easy Learning.
Output stream 2: Welcome to TutorialsPoint. Simply Easy Learning.

Apache Commons IO - TeeOutputStream Class

Overview

TeeOutputStream splits the OutputStream. It is named after the unix 'tee' command. It allows a stream to be branched to two streams.

Class Declaration

Following is the declaration for org.apache.commons.io.input.TeeOutputStream Class −

public class TeeOutputStream
   extends ProxyOutputStream

Steps of Using TeeOutputStream

Step 1: Create a TeeOutputStream for two outputstreams

// create two output streams
ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream();
ByteArrayOutputStream outputStream2 = new ByteArrayOutputStream();
TeeOutputStream teeOutputStream = new TeeOutputStream(outputStream1, outputStream2);

Step 2: Create a TeeInputStream for TeeOutputStream

// create an input stream
ByteArrayInputStream inputStream = new ByteArrayInputStream("data".getBytes("US-ASCII"));
// create teeInputStream using inputStream, teeOutputStream and closeBranch flag as true
// if closeBranch is true, outputstream is automatically closed when teeInputstream is closed.
TeeInputStream teeInputStream = new TeeInputStream(inputStream, teeOutputStream, true);

Step 3: Read Data using TeeInputStream

teeInputStream.read(new byte["data".length()]);

Step 4: Verify data in output streams

System.out.println("Output stream 1: " + outputStream1.toString());
System.out.println("Output stream 2: " + outputStream2.toString());

Step 5: Close the stream.

//teeIn.close() closes teeIn and teeOut which in turn closes the out1 and out2.
teeInputStream.close();

Example - Usage of TeeOutputStream.

CommonsIoTester.java

package com.tutorialspoint;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.apache.commons.io.input.TeeInputStream;
import org.apache.commons.io.output.TeeOutputStream;

public class CommonsIoTester {
   private static final String SAMPLE = "Welcome to TutorialsPoint. Simply Easy Learning.";
   public static void main(String[] args) {
      TeeInputStream teeInputStream = null;
      TeeOutputStream teeOutputStream = null;
      try {
         ByteArrayInputStream inputStream = new
         ByteArrayInputStream(SAMPLE.getBytes("US-ASCII"));
         ByteArrayOutputStream outputStream1 = new ByteArrayOutputStream();
         ByteArrayOutputStream outputStream2 = new ByteArrayOutputStream();
         teeOutputStream = new TeeOutputStream(outputStream1, outputStream2);
         teeInputStream = new TeeInputStream(inputStream, teeOutputStream, true);
         teeInputStream.read(new byte[SAMPLE.length()]);
         System.out.println("Output stream 1: " + outputStream1.toString());
         System.out.println("Output stream 2: " + outputStream2.toString());
      }catch (IOException e) {
         System.out.println(e.getMessage());
      } finally {
         //teeIn.close() closes teeIn and teeOut which in turn closes the out1 and out2.
         try {
            teeInputStream.close();
         } catch (IOException e) {
            System.out.println(e.getMessage());
         }
      }
   }
}

Output

It will print the following result −

Output stream 1: Welcome to TutorialsPoint. Simply Easy Learning.
Output stream 2: Welcome to TutorialsPoint. Simply Easy Learning.
Advertisements