Thursday, 20 August 2015

File utilities application using Guava package


Following is simple File utility application using guava package.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import com.google.common.base.Preconditions;
import com.google.common.io.Files;

/**
 * Contains FilieUtilities to create directories, files, properties files etc.,
 * 
 * @author harikrishna_gurram
 *
 */
public class FileUtilities {

 /**
  * Create a directory. It creates parent directories, if parent directories
  * don't exist.
  * 
  * @param directory
  */
 public static void createDirectory(String directory) {
  Preconditions.checkNotNull(directory);
  directory = directory + File.separator + "a.txt";
  File file = new File(directory);
  try {
   Files.createParentDirs(file);
  } catch (Exception e) {
   System.out.println("Unable to create directory " + directory
     + " : " + e.getMessage());
  }

 }

 /**
  * Create a file
  * 
  * @param file
  */
 public static void createFile(String file) {
  Preconditions.checkNotNull(file);
  try {
   java.nio.file.Files.createFile(Paths.get(file));
  } catch (IOException e) {
   System.out.println("Unable to create file " + file + " : "
     + e.getMessage());
   e.printStackTrace();
  }
 }

 /**
  * Append line to a file
  * 
  * @param line
  * @param to
  * @param charset
  */
 public static void appendLine(CharSequence line, String fileName,
   Charset charset) {
  Preconditions.checkNotNull(line);
  Preconditions.checkNotNull(fileName);
  Preconditions.checkNotNull(charset);

  File to = new File(fileName);

  try {
   Files.append(line, to, charset);
  } catch (IOException e) {
   System.out.println("Unable to write data to file " + to + " : "
     + e.getMessage());
  }
 }

 /**
  * Read file content as list of strings
  * 
  * @param fileName
  * @param charset
  * @return
  */
 public static List<String> readFileContent(String fileName, Charset charset) {
  Preconditions.checkNotNull(fileName);
  Preconditions.checkNotNull(charset);

  File file = new File(fileName);
  List<String> data = new ArrayList<>();

  try {
   data = Files.readLines(file, charset);
  } catch (IOException e) {
   System.out.println("Unable to read data from file " + fileName
     + " : " + e.getMessage());
  }

  return data;
 }

 /**
  * Copy file form source to destination
  * 
  * @param src
  * @param destination
  */
 public static void copyFileFrom(String src, String destination) {
  Preconditions.checkNotNull(src);
  Preconditions.checkNotNull(destination);
  Preconditions.checkArgument(!(src.equals(destination)),
    "Source and destination files are equal");

  try {
   Files.copy(new File(src), new File(destination));
  } catch (IOException e) {
   System.out.println("Unable to copy file from " + src + " to "
     + destination);
  }
 }

 /**
  * Write properties to given file. If file already exist, then properties
  * will be overridden
  * 
  * @param file
  * @param propertyMap
  */
 public static void writePropertiesToaFile(String file,
   Map<String, String> propertyMap) {
  Preconditions.checkNotNull(file);
  Preconditions.checkNotNull(propertyMap);

  try (FileOutputStream out = new FileOutputStream(file)) {
   Properties properties = new Properties();

   Set<String> keys = propertyMap.keySet();
   for (String key : keys) {
    properties.setProperty(key, propertyMap.get(key));
   }

   properties.store(out, "");
   out.close();

  } catch (Exception e) {
   System.out
     .println("Unable to get file instance to write properties "
       + e.getMessage());
  }

 }

 /**
  * Get property from a file
  * 
  * @param file
  * @param key
  * @return
  */
 public static String getPropertyFromFile(String file, String key) {
  Preconditions.checkNotNull(file);
  Preconditions.checkNotNull(key);

  String value = "unknown";
  try (FileInputStream fin = new FileInputStream(file)) {
   Properties properties = new Properties();
   properties.load(fin);
   return properties.getProperty(key);
  } catch (Exception e) {

  }
  return value;
 }

 /**
  * Returns true if a directory/file exists
  * 
  * @param fileName
  * @return
  */
 public static boolean isFileExist(String fileName) {
  Preconditions.checkNotNull(fileName);
  File file = new File(fileName);
  return file.exists();
 }

 /**
  * Get present working directory (Like pwd command of unix).
  * 
  * @return
  */
 public static String getCurrentWorkingDirectory() {
  return System.getProperty("user.dir");
 }

 /**
  * Delete a directory
  * 
  * @param directory
  */
 public static void deleteDirectory(String directory) {
  Preconditions.checkNotNull(directory);
  try {
   java.nio.file.Files.delete(Paths.get(directory));
  } catch (IOException e) {
   System.out.println("Unable to delete a directory");
  }
 }

 /**
  * Delete directory recursively
  * 
  * @param directory
  * @param recursive
  * @return
  */
 public static boolean deleteDirectory(String directory, boolean recursive) {
  Preconditions.checkNotNull(directory);

  File file = new File(directory);
  if (!file.exists()) {
   return true;
  }

  if (!recursive || !file.isDirectory())
   return file.delete();

  String[] files = file.list();
  for (int i = 0; i < files.length; i++) {
   if (!deleteDirectory(directory + File.separator + files[i], true))
    return false;
  }

  return file.delete();
 }

 /**
  * Update property file
  * 
  * @param file
  */
 public static void updatePropertyFile(String file,
   Map<String, String> properties) {

  Preconditions.checkNotNull(file);
  Preconditions.checkNotNull(properties);

  Properties props = new Properties();

  try (FileInputStream in = new FileInputStream(file)) {
   props.load(in);
  } catch (Exception e) {
   System.out.println(e.getMessage());
   return;
  }

  try (FileOutputStream out = new FileOutputStream(file)) {
   Set<String> keys = properties.keySet();
   for (String s : keys) {
    props.setProperty(s, properties.get(s));
   }
   props.store(out, "");
  } catch (Exception e) {

  }
 }

 /**
  * Update property file
  * 
  * @param file
  */
 public static void updatePropertyFile(String file, String key, String value) {
  Properties props = new Properties();

  try (FileInputStream in = new FileInputStream(file)) {
   props.load(in);
  } catch (Exception e) {
   System.out.println(e.getMessage());
   return;
  }

  try (FileOutputStream out = new FileOutputStream(file)) {
   props.setProperty(key, value);
   props.store(out, "");
  } catch (Exception e) {

  }
 }

 /* Remove specific property from a file */
 public static void removePropertyFromFile(String file, String property) {
  Properties props = new Properties();

  try (FileInputStream in = new FileInputStream(file)) {
   props.load(in);
  } catch (Exception e) {
   System.out.println(e.getMessage());
   return;
  }

  try (FileOutputStream out = new FileOutputStream(file)) {
   props.remove(property);
   props.store(out, "");
  } catch (Exception e) {

  }
 }

 /* Remove properties starts with given string */
 public static void removePropertiesStartsWithString(String file,
   String prefix) {
  Properties props = new Properties();

  try (FileInputStream in = new FileInputStream(file)) {
   props.load(in);
  } catch (Exception e) {
   System.out.println(e.getMessage());
   return;
  }

  Set<?> keys = props.keySet();
  Set<?> tempSet = new HashSet<>(keys);

  for (Object obj : tempSet) {
   String temp = (String) obj;
   if (temp.startsWith(prefix)) {
    props.remove(temp);
   }
  }

  try (FileOutputStream out = new FileOutputStream(file)) {
   props.store(out, "");
  } catch (Exception e) {

  }
 }

}


Following is the junit test case for above program.
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import java.io.File;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.Test;

import com.utils.FileUtilities;

public class FileUtilsTest {
 private static final String CURRENT_DIRECTORY = FileUtilities
   .getCurrentWorkingDirectory();;

 @Test
 public void testCreateDirectory_1() {
  String directory = CURRENT_DIRECTORY + File.separator + "temp1"
    + File.separator + "temp2";

  FileUtilities.deleteDirectory(CURRENT_DIRECTORY + File.separator
    + "temp1", true);

  FileUtilities.createDirectory(directory);

  assertTrue(FileUtilities.isFileExist(CURRENT_DIRECTORY + File.separator
    + "temp1"));
  assertTrue(FileUtilities.isFileExist(CURRENT_DIRECTORY + File.separator
    + "temp1" + File.separator + "temp2"));

  FileUtilities.deleteDirectory(CURRENT_DIRECTORY + File.separator
    + "temp1", true);

  assertFalse(FileUtilities.isFileExist(CURRENT_DIRECTORY
    + File.separator + "temp1"));
  assertFalse(FileUtilities.isFileExist(CURRENT_DIRECTORY
    + File.separator + "temp1" + File.separator + "temp2"));
 }

 @Test(expected = NullPointerException.class)
 public void testCreateDirectory_2() {
  FileUtilities.deleteDirectory(null);
 }

 @Test
 public void testCreateFile_1() {
  String file = CURRENT_DIRECTORY + File.separator + "temp.txt";
  FileUtilities.createFile(file);

  assertTrue(FileUtilities.isFileExist(file));

  FileUtilities.deleteDirectory(file);
  assertFalse(FileUtilities.isFileExist(file));

 }

 @Test(expected = NullPointerException.class)
 public void testCreateFile_2() {
  FileUtilities.createFile(null);
 }

 @Test
 public void testappendLine_1() {
  String file = CURRENT_DIRECTORY + File.separator + "temp.txt";
  FileUtilities.createFile(file);

  FileUtilities.appendLine("Line1\n", file, Charset.defaultCharset());
  FileUtilities.appendLine("Line2\n", file, Charset.defaultCharset());
  FileUtilities.appendLine("Line3", file, Charset.defaultCharset());

  List<String> data = FileUtilities.readFileContent(file,
    Charset.defaultCharset());

  int i = 1;

  for (String line : data) {
   assertEquals("Line" + i, line);
   i++;
  }

  FileUtilities.deleteDirectory(file);
  assertFalse(FileUtilities.isFileExist(file));
 }

 @Test(expected = NullPointerException.class)
 public void testappendLine_2() {
  FileUtilities.appendLine(null, null, null);
 }

 @Test(expected = NullPointerException.class)
 public void testappendLine_3() {
  FileUtilities.appendLine("line1", null, null);
 }

 @Test(expected = NullPointerException.class)
 public void testappendLine_4() {
  FileUtilities.appendLine("line1", "sample.txt", null);
 }

 @Test
 public void testReadFileContent_1() {
  String file = CURRENT_DIRECTORY + File.separator + "temp.txt";
  FileUtilities.createFile(file);

  FileUtilities.appendLine("line1\n", file, Charset.defaultCharset());
  FileUtilities.appendLine("line2\n", file, Charset.defaultCharset());
  FileUtilities.appendLine("line3\n", file, Charset.defaultCharset());

  List<String> fileNames = FileUtilities.readFileContent(file,
    Charset.defaultCharset());
  int count = 1;

  for (String s : fileNames) {
   assertTrue(s.equals("line" + count));
   count++;
  }

  FileUtilities.deleteDirectory(file);

  assertFalse(FileUtilities.isFileExist(file));
 }

 @Test(expected = NullPointerException.class)
 public void testReadFileContent_2() {
  FileUtilities.readFileContent(null, null);
 }

 @Test(expected = NullPointerException.class)
 public void testReadFileContent_3() {
  String file = CURRENT_DIRECTORY + File.separator + "temp.txt";
  FileUtilities.readFileContent(file, null);
 }

 @Test
 public void testCopyFileFrom_1() {
  String src = CURRENT_DIRECTORY + File.separator + "src.txt";
  String dest = CURRENT_DIRECTORY + File.separator + "dest.txt";

  FileUtilities.createFile(src);

  FileUtilities.appendLine("line1\n", src, Charset.defaultCharset());
  FileUtilities.appendLine("line2\n", src, Charset.defaultCharset());
  FileUtilities.appendLine("line3\n", src, Charset.defaultCharset());

  assertFalse(FileUtilities.isFileExist(dest));
  FileUtilities.copyFileFrom(src, dest);

  assertTrue(FileUtilities.isFileExist(dest));

  List<String> fileNames = FileUtilities.readFileContent(dest,
    Charset.defaultCharset());
  int count = 1;

  for (String s : fileNames) {
   assertTrue(s.equals("line" + count));
   count++;
  }

  FileUtilities.deleteDirectory(dest);
  FileUtilities.deleteDirectory(src);

  assertFalse(FileUtilities.isFileExist(src));
  assertFalse(FileUtilities.isFileExist(dest));
 }

 @Test(expected = NullPointerException.class)
 public void testCopyFileFrom_2() {
  FileUtilities.copyFileFrom(null, null);
 }

 @Test(expected = NullPointerException.class)
 public void testCopyFileFrom_3() {
  FileUtilities.copyFileFrom("", null);
 }

 @Test
 public void testWritePropertiesToaFile_1() {
  Map<String, String> properties = new HashMap<>();

  properties.put("key1", "value1");
  properties.put("key2", "value2");
  properties.put("key3", "value3");
  properties.put("key4", "value4");
  properties.put("key5", "value5");

  String file = CURRENT_DIRECTORY + File.separator + "temp.txt";

  FileUtilities.writePropertiesToaFile(file, properties);

  String val1 = FileUtilities.getPropertyFromFile(file, "key1");
  String val2 = FileUtilities.getPropertyFromFile(file, "key2");
  String val3 = FileUtilities.getPropertyFromFile(file, "key3");
  String val4 = FileUtilities.getPropertyFromFile(file, "key4");
  String val5 = FileUtilities.getPropertyFromFile(file, "key5");

  assertEquals(val1, "value1");
  assertEquals(val2, "value2");
  assertEquals(val3, "value3");
  assertEquals(val4, "value4");
  assertEquals(val5, "value5");

  FileUtilities.deleteDirectory(file);
 }

 @Test(expected = NullPointerException.class)
 public void testWritePropertiesToaFile_2() {
  FileUtilities.writePropertiesToaFile(null, null);
 }

 @Test(expected = NullPointerException.class)
 public void testWritePropertiesToaFile_3() {
  FileUtilities.writePropertiesToaFile("", null);
 }

 @Test(expected = NullPointerException.class)
 public void testGetPropertyFromFile_1() {
  FileUtilities.getPropertyFromFile(null, null);
 }

 @Test(expected = NullPointerException.class)
 public void testGetPropertyFromFile_2() {
  FileUtilities.getPropertyFromFile("", null);
 }

 @Test
 public void testUpdatePropertyFile_1() {
  Map<String, String> properties = new HashMap<>();

  properties.put("key1", "value1");
  properties.put("key2", "value2");
  properties.put("key3", "value3");
  properties.put("key4", "value4");
  properties.put("key5", "value5");

  String file = CURRENT_DIRECTORY + File.separator + "temptemp.txt";

  FileUtilities.writePropertiesToaFile(file, properties);

  Map<String, String> newProp = new HashMap<>();
  newProp.put("key6", "value6");

  FileUtilities.updatePropertyFile(file, newProp);

  String val1 = FileUtilities.getPropertyFromFile(file, "key1");
  String val2 = FileUtilities.getPropertyFromFile(file, "key2");
  String val3 = FileUtilities.getPropertyFromFile(file, "key3");
  String val4 = FileUtilities.getPropertyFromFile(file, "key4");
  String val5 = FileUtilities.getPropertyFromFile(file, "key5");
  String val6 = FileUtilities.getPropertyFromFile(file, "key6");

  assertEquals(val1, "value1");
  assertEquals(val2, "value2");
  assertEquals(val3, "value3");
  assertEquals(val4, "value4");
  assertEquals(val5, "value5");
  assertEquals(val6, "value6");

  FileUtilities.deleteDirectory(file);

 }

 @Test
 public void testUpdatePropertyFile_2() {
  Map<String, String> properties = new HashMap<>();

  properties.put("key1", "value1");
  properties.put("key2", "value2");
  properties.put("key3", "value3");
  properties.put("key4", "value4");
  properties.put("key5", "value5");

  String file = CURRENT_DIRECTORY + File.separator + "temptemp.txt";

  FileUtilities.writePropertiesToaFile(file, properties);

  Map<String, String> newProp = new HashMap<>();
  newProp.put("key6", "value6");

  FileUtilities.updatePropertyFile(file, "key5", "value6");
  FileUtilities.updatePropertyFile(file, "key6", "value7");

  String val1 = FileUtilities.getPropertyFromFile(file, "key1");
  String val2 = FileUtilities.getPropertyFromFile(file, "key2");
  String val3 = FileUtilities.getPropertyFromFile(file, "key3");
  String val4 = FileUtilities.getPropertyFromFile(file, "key4");
  String val5 = FileUtilities.getPropertyFromFile(file, "key5");
  String val6 = FileUtilities.getPropertyFromFile(file, "key6");

  assertEquals(val1, "value1");
  assertEquals(val2, "value2");
  assertEquals(val3, "value3");
  assertEquals(val4, "value4");
  assertEquals(val5, "value6");
  assertEquals(val6, "value7");

  FileUtilities.deleteDirectory(file);

 }

 @Test
 public void testRemovePropertyFromFile() {
  Map<String, String> properties = new HashMap<>();

  properties.put("key1", "value1");
  properties.put("key2", "value2");
  properties.put("key3", "value3");
  properties.put("key4", "value4");
  properties.put("key5", "value5");

  String file = CURRENT_DIRECTORY + File.separator + "temptemp.txt";
  FileUtilities.writePropertiesToaFile(file, properties);

  FileUtilities.removePropertyFromFile(file, "key1");

  String val1 = FileUtilities.getPropertyFromFile(file, "key1");
  String val2 = FileUtilities.getPropertyFromFile(file, "key2");
  String val3 = FileUtilities.getPropertyFromFile(file, "key3");
  String val4 = FileUtilities.getPropertyFromFile(file, "key4");
  String val5 = FileUtilities.getPropertyFromFile(file, "key5");
  String val6 = FileUtilities.getPropertyFromFile(file, "key6");

  assertEquals(val1, null);
  assertEquals(val2, "value2");
  assertEquals(val3, "value3");
  assertEquals(val4, "value4");
  assertEquals(val5, "value5");
  assertEquals(val6, null);

  FileUtilities.deleteDirectory(file);
 }

 
}




No comments:

Post a Comment