How to Move/Rename File from Internal App Storage to External Storage on Android

How to move/rename file from internal app storage to external storage on Android?

To copy files from internal memory to SD card and vice-versa using following piece of code:

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

And - it works...

How to move a file from my app's internal storage to the phone's download directory in Android Q (10)?

You have two options.

Use Storage Acces Framework to let the user choose the Download directory .

Use MediaStore to insert file to Download directory.

Android copy file from internal storage to external

Try some thing like this:

 new FileAsyncTask().execute(files);

and

// AsyncTask for Background Process

private class FileAsyncTask extends AsyncTask<ArrayList<String>, Void, Void> {         
ArrayList<String> files;
ProgressDialog dialog;
@Override
protected void onPreExecute() {
dialog = ProgressDialog.show(ActivityName.this, "Your Title", "Loading...");
}
@Override
protected Void doInBackground(ArrayList<String>... params) {
files = params[0];
for (int i = 0; i < files.size(); i++) {
copyFileToSDCard(files.get(i));
} return null;
}
@Override
protected void onPostExecute(Void result) {
dialog.dismiss();
}
}

// Function to copy file to the SDCard

public void copyFileToSDCard(String fileFrom){
AssetManager is = this.getAssets();
InputStream fis;
try {

fis = is.open(fileFrom);
FileOutputStream fos;
if (!APP_FILE_PATH.exists()) {
APP_FILE_PATH.mkdirs();
}
fos = new FileOutputStream(new File(Environment.getExternalStorageDirectory()+"/MyProject", fileFrom));
byte[] b = new byte[8];
int i;
while ((i = fis.read(b)) != -1) {
fos.write(b, 0, i);
}
fos.flush();
fos.close();
fis.close();
}
catch (IOException e1) {
e1.printStackTrace();
}
}

public static boolean copyFile(String from, String to) {
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(from);
if (oldfile.exists()) {
InputStream inStream = new FileInputStream(from);
FileOutputStream fs = new FileOutputStream(to);
byte[] buffer = new byte[1444];
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread;
fs.write(buffer, 0, byteread);
}
inStream.close();
fs.close();
}
return true;
} catch (Exception e) {
return false;
}
}


Related Topics



Leave a reply



Submit