Monday, 25 April 2016

How to rename, move or copy files ?


Rename file
File oldfile = new File("oldfile.txt");
File newfile = new File("newfile.txt");
if(oldfile.renameTo(newfile))
  System.out.println("Rename succesful");
else

  System.out.println("Rename failed");


Move file - Rename file but at different location
File afile = new File("C:\\folderA\\Afile.txt");
File bFile = new File("C:\\folderB\\" + afile.getName());
if(afile.renameTo(bFile))
  System.out.println("File is moved successful!");
else
  System.out.println("File is failed to move!");


Copy File
InputStream inStream = null;
OutputStream outStream = null;
try{
  File afile = new File("Afile.txt");
  File bfile = new File("Bfile.txt");
  inStream = new FileInputStream(afile);
  outStream = new FileOutputStream(bfile);

  byte[] buffer = new byte[1024];
  int length;
  //copy the file content in bytes
  while ((length = inStream.read(buffer)) > 0){
     outStream.write(buffer, 0, length);
  }

  inStream.close();
  outStream.close();
  System.out.println("File is copied successful!");
}catch(IOException e){
  e.printStackTrace();

}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.