Re: File reading/writing using nio API from JDK 1.4 beta3
Posted By:
Alex_Zakotyanskiy
Posted On:
Monday, December 10, 2001 01:16 PM
/**
* Copy file from source to destination directory.
* The source and destination directory must exist.
* @param File to copy from
* @param Source directory to copy from
* @param Destination directory to copy to
* @param Indicating whether the file in source directory should be deleted.
* @return boolean false if an error has occured, true otherwise.
*/
public static boolean copyFile(String fileName, String sourceDirectory, String destinationDirectory, boolean deleteFromSource)
throws FileNotFoundException, IOException
{
boolean isCopied ;
byte buffer[] = new byte[1024];
int total;
// Define source and destination directory objects to copy files.
//
File fSourceDirectory = new File(sourceDirectory);
File fDestinationDirectory = new File(destinationDirectory);
// Check if directories exist.
//
boolean isSourceExists = fSourceDirectory.isDirectory();
boolean isDestinationExists = fSourceDirectory.isDirectory();
if(isSourceExists && isDestinationExists)
{
if(fileName != null)
{
// Create a new file in distination directory.
//
File in = new File(sourceDirectory, fileName);
File out = new File(destinationDirectory, fileName);
out.createNewFile();
RandomAccessFile write = new RandomAccessFile(out, "rw");
// Check if file is not empty and then copy
// the contents of the file.
//
if(in.length() > 0)
{
RandomAccessFile read = new RandomAccessFile(in, "rw");
// Reads bytes of data from the file into an array of bytes.
//
while ((total = read.read(buffer)) > 0)
{
write.write(buffer, 0, total);
}
read.close();
}
write.close();
// Delete file from the source directory.
//
if(deleteFromSource)
{
in.delete();
}
isCopied = true;
}
}
return isCopied;
}