How to Make a Copy of a File in Android

How to make a copy of a file in android?

To copy a file and save it to your destination path you can use the method below.

public static void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
try {
OutputStream out = new FileOutputStream(dst);
try {
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
} finally {
out.close();
}
} finally {
in.close();
}
}

On API 19+ you can use Java Automatic Resource Management:

public static void copy(File src, File dst) throws IOException {
try (InputStream in = new FileInputStream(src)) {
try (OutputStream out = new FileOutputStream(dst)) {
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
}
}
}

How to copy a file to another directory programmatically?

You can use these functions. The first one will copy whole directory with all children or a single file if you pass in a file. The second one is only usefull for files and is called for each file in the first one.

Also note you need to have permissions to do that

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

Functions:

 public static void copyFileOrDirectory(String srcDir, String dstDir) {

try {
File src = new File(srcDir);
File dst = new File(dstDir, src.getName());

if (src.isDirectory()) {

String files[] = src.list();
int filesLength = files.length;
for (int i = 0; i < filesLength; i++) {
String src1 = (new File(src, files[i]).getPath());
String dst1 = dst.getPath();
copyFileOrDirectory(src1, dst1);

}
} else {
copyFile(src, dst);
}
} catch (Exception e) {
e.printStackTrace();
}
}

public static void copyFile(File sourceFile, File destFile) throws IOException {
if (!destFile.getParentFile().exists())
destFile.getParentFile().mkdirs();

if (!destFile.exists()) {
destFile.createNewFile();
}

FileChannel source = null;
FileChannel destination = null;

try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
destination.transferFrom(source, 0, source.size());
} finally {
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
}

Android: copying files from one directory to another

It runs good after amended in the following way:

    button1_save.setOnClickListener(new OnClickListener() 
{
public void onClick(View v)
{
String sourcePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/TongueTwister/tt_temp.3gp";
File source = new File(sourcePath);

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

Copy file from the internal to the external storage in Android

I solved my issue. The problem was in the destination path, in the original code:

File dst = new File(dstPath);

the variable dstPath had the full destination path, including the name of the file, which is wrong. Here is the correct code fragment:

String dstPath = Environment.getExternalStorageDirectory() + File.separator + "myApp" + File.separator;
File dst = new File(dstPath);

exportFile(pictureFile, dst);

private File exportFile(File src, File dst) throws IOException {

//if folder does not exist
if (!dst.exists()) {
if (!dst.mkdir()) {
return null;
}
}

String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File expFile = new File(dst.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
FileChannel inChannel = null;
FileChannel outChannel = null;

try {
inChannel = new FileInputStream(src).getChannel();
outChannel = new FileOutputStream(expFile).getChannel();
} catch (FileNotFoundException e) {
e.printStackTrace();
}

try {
inChannel.transferTo(0, inChannel.size(), outChannel);
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}

return expFile;
}

Thanks for the tips.

How to move/copy any type of file from asset file to scoped storage ANDROID Q in JAVA?

I finally find a solution, I pretty sure it's not the best way but it work.
I give me access to all files acccess by this way :

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){
try {
Intent intentFiles = new Intent();
intentFiles.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
Uri uriFiles = Uri.fromParts("package", myContext.getPackageName(), null);
intentFiles.setData(uriFiles);
myContext.startActivity(intentFiles);
} catch (Exception e)
{
Intent intentFiles = new Intent();
intentFiles.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
myContext.startActivity(intentFiles);
}

add this line to your manifest:

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

after that, this code below work :

AssetManager assetManager = Objects.requireNonNull(requireContext()).getAssets();
Context myContext = requireContext();
//Essential for creating the external storage directory for the first launch
myContext.getExternalFilesDir(null);
File databasesFolder = new File(myContext.getExternalFilesDir(null).getParent(), "com.mydb.orca/databases");
databasesFolder.mkdirs();

if (files!= null) {
for (String filename : files) {
InputStream in;
OutputStream out;
try {
in = assetManager.open("database/test/" + filename);
File outFile = new File(databasesFolder, filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
in.close();
out.flush();
out.close();
} catch (IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
}
} else {
Log.e("Error NPE", "files is null");
}

private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}

}

if someone have a best solution it should be nice

I tested on android 11 and it work

FileSystemException: Cannot copy file (OS Error: Operation not permitted, errno = 1)

/storage/emulated/0/Documents/myapp/folder/folder/97897897/records/2022-03-30 08:26:14.098976.png

There is no reason why you would not be able to create a file in those subdirectories of public Documents folder. Be it that you create those subdirectories first. Just the usual WRITE permission needed. So no MANAGE_EXTERNAL_STORAGE needed.

But a filename like ....08:26:14.098976.png will not go as it contains forbidden characters :.

Replace them by someting more suitable.



Related Topics



Leave a reply



Submit