1 package com.android.wallpaper.util;
2 
3 import android.content.Context;
4 
5 import java.io.File;
6 import java.io.FileInputStream;
7 import java.io.FileOutputStream;
8 import java.io.IOException;
9 import java.nio.channels.FileChannel;
10 
11 /**
12  * Common utility methods for moving app files around.
13  */
14 public class FileMover {
15 
16     /**
17      * Moves a file from the {@code srcContext}'s files directory to the files directory for the
18      * given {@code dstContext}.
19      * @param srcContext {@link Context} used to open the file corresponding to srcFileName
20      * @param srcFileName Name of the source file (just the name, no path). It's expected to be
21      *                    located in {@link Context#getFilesDir()} for {@code srcContext}
22      * @param dstContext {@link Context} used to open the file corresponding to dstFileName
23      * @param dstFileName Name of the destination file (just the name, no path), which will be
24      *                    located in {@link Context#getFilesDir()} for {@code dstContext}
25      * @return a {@link File} corresponding to the moved file in its new location, or null if
26      *      nothing was moved (because srcFileName didn't exist).
27      */
moveFileBetweenContexts(Context srcContext, String srcFileName, Context dstContext, String dstFileName)28     public static File moveFileBetweenContexts(Context srcContext, String srcFileName,
29                                                Context dstContext, String dstFileName)
30             throws IOException {
31         File srcFile = srcContext.getFileStreamPath(srcFileName);
32         if (srcFile.exists()) {
33             try (FileInputStream input = srcContext.openFileInput(srcFileName);
34                  FileOutputStream output = dstContext.openFileOutput(
35                          dstFileName, Context.MODE_PRIVATE)) {
36                 FileChannel inputChannel = input.getChannel();
37                 inputChannel.transferTo(0, inputChannel.size(), output.getChannel());
38                 output.flush();
39                 srcContext.deleteFile(srcFileName);
40             }
41             return dstContext.getFileStreamPath(dstFileName);
42         }
43         return null;
44     }
45 }
46