Saturday, November 10, 2012

Awesome Java NIO

Easy File Reading

public static List getNamesFromFile(String filetoread)
{
 List lines = null;    
 try
 {
  lines = Files.readAllLines(Paths.get(filetoread), Charset.forName("UTF-8"));
 }
 catch(Exception e)
 {
  System.out.println("Error reading list file \n " + e);     
 }

 return lines;
} // end getNames




Easy File Copy

public static void copyFile(File src, File dest) throws IOException
{
 if (!src.exists())
 {
  // either return quietly OR throw an exception
  return;
 }

 if (!dest.exists())
 {
  dest.createNewFile();
 }

 try
 {
  FileChannel source = new FileInputStream(src).getChannel();
  FileChannel destination = new FileOutputStream(dest).getChannel();

  try
  {
   source.transferTo(0, source.size(), destination);
   // destination.transferFrom(source, 0, source.size());
  }
  finally
  {
   if (destination != null)
   {
    destination.close();
   }
  }
 }
 finally
 {
  if (source != null)
  {
   source.close();
  }
 }

} // function ends

 


Neo here is new NIO. -S