Apache Commons IO – FileAlterationObserver

Apache Commons IO – FileAlterationObserver ”; Previous Next FileAlterationObserver 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 Example of FileAlterationObserver Class Here is the input file we need to parse − Welcome to TutorialsPoint. Simply Easy Learning. IOTester.java 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 IOTester { public static void main(String[] args) { try { usingFileAlterationObserver(); } catch(IOException e) { System.out.println(e.getMessage()); } } public static void usingFileAlterationObserver() throws IOException { //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 = new FileAlterationObserver(parentDirectory); observer.addListener(new FileAlterationListenerAdaptor() { @Override public void onDirectoryCreate(File file) { System.out.println(“Folder created: ” + file.getName()); } @Override public void onDirectoryDelete(File file) { System.out.println(“Folder deleted: ” + file.getName()); } @Override public void onFileCreate(File file) { System.out.println(“File created: ” + file.getName()); } @Override public void onFileDelete(File file) { Syst em.out.println(“File deleted: ” + 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); FileDeleteStrategy.NORMAL.delete(newFolder); Thread.sleep(1000); FileDeleteStrategy.NORMAL.delete(newFile); 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 Folder deleted: test File deleted: test1 Print Page Previous Next Advertisements ”;

Apache Commons IO – Discussion

Discuss Apache Commons IO ”; Previous Next The Apache Commons IO are the components of the Apache Commons, which are derived from Java API and provides various utility classes for common operations for File io covering wide range of use cases. It helps avoid writing boilerplate code. This tutorial covers most of the topics required for a basic understanding of Apache Commons IO and to get a feel of how it works. Print Page Previous Next Advertisements ”;

Apache Commons IO – FilenameUtils

Apache Commons IO – FilenameUtils ”; Previous Next Provides method 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:devprojectfile.txt. Then the components are − Prefix – C: Relative Path – devproject Absolute path – C:devproject Name – file.txt Base name – file Extension – txt To identify a directory, add a separator to file name. Example of FilenameUtils Class An example of FilenameUtils Class is given below − IOTester.java import java.io.IOException; import org.apache.commons.io.FilenameUtils; public class IOTester { public static void main(String[] args) { try { //Using FilenameUtils usingFilenameUtils(); } catch(IOException e) { System.out.println(e.getMessage()); } } public static void usingFilenameUtils() 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)); System.out.println(“Extension: ” + FilenameUtils.getExtension(path)); System.out.println(“Base: ” + FilenameUtils.getBaseName(path)); System.out.println(“Name: ” + FilenameUtils.getName(path)); String filename = “C:/commons/io/../lang/project.xml”; System.out.println(“Normalized Path: ” + FilenameUtils.normalize(filename)); } } Output It will print the following result. Full Path: C:devproject Relative Path: devproject Prefix: C: Extension: txt Base: file Name: file.txt Normalized Path: C:commonslangproject.xml Print Page Previous Next Advertisements ”;

Apache Commons IO – Quick Guide

Apache Commons IO – Quick Guide ”; Previous Next 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. Apache Commons IO library provides classes for following categories: Utility classes − These classes 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 works 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 under org.apache.commons.io.filefilter package provides methods to filter files based on logical criterias 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 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 filesystem and notifies listeners of create, change or delete events. FileAlterationMonitor − Represent 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. CountingOutputStream − Counts the number of bytes passed through the stream. ProxyOutputStream − Changes the calls to proxied stream. LockableFileWriter − A FileWriter to create lock files and allow simple cross thread file lock handling. Apache Commons IO – Environment Setup In this chapter, we will learn about the local environment setup of Apache Commons IO and how to set up the path of Commons IO for Windows 2000/XP, Windows 95/98/ME etc. We will also understand about some popular java editors and how to download Commons IO archive. Local Environment Setup System Requirements JDK Java SE 2 JDK 1.8 or above Memory 1 GB RAM (recommended) Disk Space No minimum requirement Operating System Version Windows XP or above, Linux Verify your Java Installation First of all, you need to have Java Software Development Kit (SDK) installed on your system. To verify this, execute any of the two commands depending on the platform you are working on. If the Java installation has been done properly, then it will display the current version and specification of your Java installation. A sample output is given in the following table. Platform Command Sample Output Windows Open command console and type − >java -version java version “11.0.11” 2021-04-20 LTS Java(TM) SE Runtime Environment 18.9 (build 11.0.11+9-LTS-194) Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.11+9-LTS-194, mixed mode) Linux Open command terminal and type − $java -version java version “11.0.11” 2021-04-20 LTS Open JDK Runtime Environment 18.9 (build 11.0.11+9-LTS-194) Open JDK 64-Bit Server VM (build 11.0.11+9-LTS-194, mixed mode) We assume the readers of this tutorial have Java SDK version 11.0.11 installed on their system. In case you do not have Java SDK, download its current version from www.oracle.com/technetwork/java/javase/downloads/index.html and have it installed. Set your Java Environment Set the environment variable JAVA_HOME to point to the base directory location where Java is installed on your machine. For example, Sr.No. Platform & Description 1 Windows Set JAVA_HOME to C:ProgramFilesjavajdk11.0.11 2 Linux Export JAVA_HOME = /usr/local/java-current Append the full path of Java compiler location to the System Path. Sr.No. Platform & Description 1 Windows Append the String “C:Program FilesJavajdk11.0.11bin” to the end of the system variable PATH. 2 Linux Export PATH = $PATH:$JAVA_HOME/bin/

Apache Commons IO – OrFileFilter

Apache Commons IO – OrFileFilter ”; Previous Next OrFileFilter 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 Example of OrFileFilter Class Here is the input file we need to parse − Welcome to TutorialsPoint. Simply Easy Learning. Let”s print all files and directories in the current directory and then, filter a file with name starting with . or ends with t. IOTester.java import java.io.File; import java.io.IOException; import org.apache.commons.io.filefilter.OrFileFilter; import org.apache.commons.io.filefilter.PrefixFileFilter; import org.apache.commons.io.filefilter.WildcardFileFilter; public class IOTester { public static void main(String[] args) { try { usingOrFileFilter(); } catch(IOException e) { System.out.println(e.getMessage()); } } public static void usingOrFileFilter() 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]); } System.out.println(“nFile starting with . or ends with tn”); String[] filesNames = currentDirectory.list( new OrFileFilter(new PrefixFileFilter(“.”), new WildcardFileFilter(“*t”))); for( int i = 0; i < filesNames.length; i++ ) { System.out.println(filesNames[i]); } } } Output It will print the following result. All files and Folders. .classpath .project .settings bin input.txt src File starting with . or ends with t .classpath .project .settings input.txt Print Page Previous Next Advertisements ”;

Apache Commons IO – Environment Setup

Apache Commons IO – Environment Setup ”; Previous Next In this chapter, we will learn about the local environment setup of Apache Commons IO and how to set up the path of Commons IO for Windows 2000/XP, Windows 95/98/ME etc. We will also understand about some popular java editors and how to download Commons IO archive. Local Environment Setup System Requirements JDK Java SE 2 JDK 1.8 or above Memory 1 GB RAM (recommended) Disk Space No minimum requirement Operating System Version Windows XP or above, Linux Verify your Java Installation First of all, you need to have Java Software Development Kit (SDK) installed on your system. To verify this, execute any of the two commands depending on the platform you are working on. If the Java installation has been done properly, then it will display the current version and specification of your Java installation. A sample output is given in the following table. Platform Command Sample Output Windows Open command console and type − >java -version java version “11.0.11” 2021-04-20 LTS Java(TM) SE Runtime Environment 18.9 (build 11.0.11+9-LTS-194) Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.11+9-LTS-194, mixed mode) Linux Open command terminal and type − $java -version java version “11.0.11” 2021-04-20 LTS Open JDK Runtime Environment 18.9 (build 11.0.11+9-LTS-194) Open JDK 64-Bit Server VM (build 11.0.11+9-LTS-194, mixed mode) We assume the readers of this tutorial have Java SDK version 11.0.11 installed on their system. In case you do not have Java SDK, download its current version from www.oracle.com/technetwork/java/javase/downloads/index.html and have it installed. Set your Java Environment Set the environment variable JAVA_HOME to point to the base directory location where Java is installed on your machine. For example, Sr.No. Platform & Description 1 Windows Set JAVA_HOME to C:ProgramFilesjavajdk11.0.11 2 Linux Export JAVA_HOME = /usr/local/java-current Append the full path of Java compiler location to the System Path. Sr.No. Platform & Description 1 Windows Append the String “C:Program FilesJavajdk11.0.11bin” to the end of the system variable PATH. 2 Linux Export PATH = $PATH:$JAVA_HOME/bin/ Execute the command java -version from the command prompt as explained above. Popular Java Editors To write your Java programs, you need a text editor. There are many sophisticated integrated development environment (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.11.0-bin.zip. At the time of writing this tutorial, we have downloaded commons-io-2.11.0-bin.zip and copied it into C:>Apache folder. OS Archive name Windows commons-io-2.11.0-bin.zip Linux commons-io-2.11.0-bin.tar.gz Mac commons-io-2.11.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.11.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.11.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.11.0.jar;. Linux export CLASSPATH=$CLASSPATH:$APACHE_HOME/commons-io-2.11.0.jar:. Mac export CLASSPATH=$CLASSPATH:$APACHE_HOME/commons-io-2.11.0.jar:. Print Page Previous Next Advertisements ”;

Apache Commons IO – FileSystemUtils

Apache Commons IO – FileSystemUtils ”; Previous Next FileSystemUtils provide 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 of FileSystemUtils Class Given below is the example of FileSystemUtils Class − IOTester.java import java.io.IOException; import org.apache.commons.io.FileSystemUtils; public class IOTester { public static void main(String[] args) { try { System.out.println(“Free Space ” + FileSystemUtils.freeSpaceKb(“C:/”) + ” Bytes”); } catch(IOException e) { System.out.println(e.getMessage()); } } } Output It will print the following result − Free Space 61355640 kb Print Page Previous Next Advertisements ”;

Apache Commons IO – FileAlterationMonitor

Apache Commons IO – FileAlterationMonitor ”; Previous Next FileAlterationMonitor 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 final class FileAlterationMonitor extends Object implements Runnable Example of FileAlterationMonitor Class Here is the input file we need to parse − Welcome to TutorialsPoint. Simply Easy Learning. IOTester.java 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 IOTester { public static void main(String[] args) { try { usingFileAlterationMonitor(); } catch(IOException e) { System.out.println(e.getMessage()); } } public static void usingFileAlterationMonitor() throws IOException { //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 = new FileAlterationObserver(parentDirectory); observer.addListener(new FileAlterationListenerAdaptor(){ @Override public void onDirectoryCreate(File file) { System.out.println(“Folder created: ” + file.getName()); } @Override public void onDirectoryDelete(File file) { System.out.println(“Folder deleted: ” + file.getName()); } @Override public void onFileCreate(File file) { System.out.println(“File created: ” + 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); 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); FileDeleteStrategy.NORMAL.delete(newFolder); Thread.sleep(1000); FileDeleteStrategy.NORMAL.delete(newFile); 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 Folder deleted: test File deleted: test1 Print Page Previous Next Advertisements ”;

Apache Commons IO – TeeInputStream

Apache Commons IO – TeeInputStream ”; Previous Next It 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 Example of TeeInputStream Class In this example, closing a TeeInputStream closes the TeeInputStream as well as the TeeOutputStream objects. IOTester.java 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 IOTester { 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. Print Page Previous Next Advertisements ”;

Apache Commons IO – WildcardFileFilter

Apache Commons IO – WildcardFileFilter ”; Previous Next WildcardFileFilter 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 Example of WildcardFileFilter Class Here is the input file we need to parse Welcome to TutorialsPoint. Simply Easy Learning. Let”s print all files and directories in the current directory and then, filter a file whose name ends with t. IOTester.java import java.io.File; import java.io.IOException; import org.apache.commons.io.filefilter.WildcardFileFilter; public class IOTester { public static void main(String[] args) { try { usingWildcardFileFilter(); } catch(IOException e) { System.out.println(e.getMessage()); } } public static void usingWildcardFileFilter() 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]); } System.out.println(“nFile name ending with t.n”); String[] filesNames = currentDirectory.list( new WildcardFileFilter(“*t”)); for( int i = 0; i < filesNames.length; i++ ) { System.out.println(filesNames[i]); } } } Output It will print the following result. All files and Folders. .classpath .project .settings bin input.txt src File name ending with t .project input.txt Print Page Previous Next Advertisements ”;