Guava Files Tutorial

Unfortunately, the out-of-the-box tools for manipulating files, as well as, reading, and writing files Java provides are not as streamlined as they could be. Guava provides a number of utilities for working with Java File objects.

Copying Files

Copying files in Java is a tedious task. Guava provides a way to copy files in a single line of code, such as in the example below:


File source = new File("source.txt");
File destination = new File("destination.txt");
Files.copy(source, destination);

To accomplish the same thing in Java would require a number of lines of code and isn’t very straightforward, as shown:


InputStream is = null;
OutputStream os = null;

try
{
   is = new FileInputStream(new File("source.txt"));
   os = new FileOutputStream(new File("destination.txt"));
   byte[] buffer = new byte[1024];
   int totalBytesRead;
   while ((totalBytesRead = is.read(buf)) > 0)
   {
      os.write(buf, 0, bytesRead);
   }
}
finally
{
   is.close();
   os.close();
}

Moving or Renaming Files

Moving or renaming files in Java is of similar difficulty as copying a file. Guava also provides a simple utility method to move files. To move a file, simply execute the code shown below:


File source = new File("source.txt");
File destination = new File("destination.txt");

try
{
   Files.move(source, destination);
}
catch(IOException e)
{
   e.printStackTracke();
}

Retrieving the File Extension of a File

Guava provides a number of other basic utilities for working with files. One such utility is the static getFileExtension(String fullName) method. It returns the provided file extension of the given file name as illustrated:


String fileName = "source.txt";
String extension = Files.getFileExtension(fileName);
System.out.println(extension); // prints "txt"