Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically move, copy and delete files and directories on SD?

I want to programmatically move, copy and delete files and directories on SD card. I've done a Google search but couldn't find anything useful.

like image 476
Tony Avatar asked Nov 14 '10 15:11

Tony


People also ask

Is move the same as copy delete?

In Windows, at least, move is simply a more automated Copy&Delete.


1 Answers

set the correct permissions in the manifest

     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

below is a function that will programmatically move your file

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());     }  } 

To Delete the file use

private void deleteFile(String inputPath, String inputFile) {     try {         // delete the original file         new File(inputPath + inputFile).delete();       }     catch (Exception e) {         Log.e("tag", e.getMessage());     } } 

To copy

private void copyFile(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 (You have now copied the file)             out.flush();         out.close();         out = null;              }  catch (FileNotFoundException fnfe1) {         Log.e("tag", fnfe1.getMessage());     }             catch (Exception e) {         Log.e("tag", e.getMessage());     }  } 
like image 81
Daniel Leahy Avatar answered Oct 02 '22 16:10

Daniel Leahy