How to copy my files from one directory to another directory?

I am working on Android. My requirement is that I have one directory with some files, later I uploaded some other files to another directory, and I'm going to copy all the files from the last directory to the first directory. And before copying files to the first directory from the latter, I need to delete all files from the first directory.

+6
source share
3 answers
void copyFile(File src, File dst) throws IOException { FileChannel inChannel = new FileInputStream(src).getChannel(); FileChannel outChannel = new FileOutputStream(dst).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } 

I cannot remember where I found this, but it was from a useful article that I used to back up the SQLite database.

+21
source

Apache FileUtils makes it very simple and beautiful.

enable apache package for sharing add commons-io.jar

or

commons-io android gradle dependency

  compile 'commons-io:commons-io:2.4' 

Add this code

 String sourcePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/TongueTwister/sourceFile.3gp"; File source = new File(sourcePath); String destinationPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/TongueTwister/destFile.3gp"; File destination = new File(destinationPath); try { FileUtils.copyFile(source, destination); } catch (IOException e) { e.printStackTrace(); } 
+5
source

You should also use the code below:

 public static void copyDirectoryOneLocationToAnotherLocation(File sourceLocation, File targetLocation) throws IOException { if (sourceLocation.isDirectory()) { if (!targetLocation.exists()) { targetLocation.mkdir(); } String[] children = sourceLocation.list(); for (int i = 0; i < sourceLocation.listFiles().length; i++) { copyDirectoryOneLocationToAnotherLocation(new File(sourceLocation, children[i]), new File(targetLocation, children[i])); } } else { InputStream in = new FileInputStream(sourceLocation); OutputStream out = new FileOutputStream(targetLocation); // Copy the bits from instream to outstream byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); } } 
0
source

Source: https://habr.com/ru/post/910160/


All Articles