FileUtil.java

  1. /*******************************************************************************
  2.  * Copyright 2013 André Rouél
  3.  *
  4.  * Licensed under the Apache License, Version 2.0 (the "License");
  5.  * you may not use this file except in compliance with the License.
  6.  * You may obtain a copy of the License at
  7.  *
  8.  *   http://www.apache.org/licenses/LICENSE-2.0
  9.  *
  10.  * Unless required by applicable law or agreed to in writing, software
  11.  * distributed under the License is distributed on an "AS IS" BASIS,
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13.  * See the License for the specific language governing permissions and
  14.  * limitations under the License.
  15.  ******************************************************************************/
  16. package net.sf.uadetector.internal.util;

  17. import java.io.BufferedReader;
  18. import java.io.File;
  19. import java.io.FileInputStream;
  20. import java.io.IOException;
  21. import java.io.InputStreamReader;
  22. import java.nio.charset.Charset;

  23. /**
  24.  * This class is intended to provide file utility functions.
  25.  *
  26.  * @author André Rouél
  27.  */
  28. public final class FileUtil {

  29.     /**
  30.      * Checks if the given file is empty.
  31.      *
  32.      * @param file
  33.      *            the file that could be empty
  34.      * @return {@code true} when the file is accessible and empty otherwise {@code false}
  35.      * @throws IOException
  36.      *             if an I/O error occurs
  37.      */
  38.     public static boolean isEmpty(final File file, final Charset charset) throws IOException {
  39.         boolean empty = false;
  40.         BufferedReader reader = null;
  41.         boolean threw = true;
  42.         try {
  43.             reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
  44.             final String line = reader.readLine();
  45.             empty = line == null;
  46.             threw = false;
  47.         } finally {
  48.             Closeables.close(reader, threw);
  49.         }
  50.         return empty;
  51.     }

  52.     /**
  53.      * <strong>Attention:</strong> This class is not intended to create objects from it.
  54.      */
  55.     private FileUtil() {
  56.         // This class is not intended to create objects from it.
  57.     }

  58. }