Provides utility methods for reading, writing and copying files. The methods works with InputStream, OutputStream, Reader and Writer.

Class Declaration

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

  1. public class IOUtils
  2. extends Object

Features

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

Example of IOUtils Class

Here is the input file we need to parse −

  1. Welcome to TutorialsPoint. Simply Easy Learning.

IOTester.java

  1. import java.io.BufferedReader;
  2. import java.io.FileInputStream;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.InputStreamReader;
  6.  
  7. import org.apache.commons.io.IOUtils;
  8.  
  9. public class IOTester {
  10. public static void main(String[] args) {
  11. try {
  12. //Using BufferedReader
  13. readUsingTraditionalWay();
  14.  
  15. //Using IOUtils
  16. readUsingIOUtils();
  17. } catch(IOException e) {
  18. System.out.println(e.getMessage());
  19. }
  20. }
  21.  
  22. //reading a file using buffered reader line by line
  23. public static void readUsingTraditionalWay() throws IOException {
  24. try(BufferedReader bufferReader
  25. = new BufferedReader( new InputStreamReader(
  26. new FileInputStream("input.txt") ) )) {
  27. String line;
  28. while( ( line = bufferReader.readLine() ) != null ) {
  29. System.out.println( line );
  30. }
  31. }
  32. }
  33.  
  34. //reading a file using IOUtils in one go
  35. public static void readUsingIOUtils() throws IOException {
  36. try(InputStream in = new FileInputStream("input.txt")) {
  37. System.out.println( IOUtils.toString( in , "UTF-8") );
  38. }
  39. }
  40. }

Output

It will print the following result.

  1. Welcome to TutorialsPoint. Simply Easy Learning.
  2. Welcome to TutorialsPoint. Simply Easy Learning.