Wednesday, 7 May 2014

Moving a File From One Directory To Another Directory In Android Programmatically (SIMPLE)

SourceFilePath is the current  path of which file you are going to move

DestinationFilePath is the path where you are going to move that file

File SourceFile = new File(SourceFilePath);
   
File DestinationFile = new File(DestinationFilePath);
        
if(SourceFile.renameTo(DestinationFile))    
{
      Log.v("Moving", "Moving file successful."); 
}
else
{
      Log.v("Moving", "Moving file failed.");
}

Moving a File From One Directory To Another Directory In Android Programmatically

private void moveFile(String inputPath, String inputFile, String outputPath) 
{
    InputStream in = null;
    OutputStream out = null;
    try 
    {
        //create output directory if it doesn't exist
        File dir = new File (outputPath); 
        if (!dir.exists())
        {
            dir.mkdirs();
        }

        in = new FileInputStream(inputPath + inputFile);        
        out = new FileOutputStream(outputPath + inputFile);

        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1) {
        out.write(buffer, 0, read);
        }
        in.close();
        in = null;

        // write the output file
        out.flush();
        out.close();
        out = null;

        // delete the original file
        new File(inputPath + inputFile).delete();  
    } 
    catch (FileNotFoundException fnfe1) {
    Log.e("tag", fnfe1.getMessage());
    }
    catch (Exception e) {
    Log.e("tag", e.getMessage());
    }
}