How to programmatically move, copy and delete files and directories on SD?
Use standard Java I/O. Use Environment.getExternalStorageDirectory()
to get to the root of external storage (which, on some devices, is an SD card).
How to programmatically move , copy files to SD?
This is how I finally solved the issue.
First call an intent to let the user grant write permission for whole SD card.
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivityForResult(intent, 42);
Then on onActivityResult take write permission.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
treeUri = data.getData();
final int takeFlags = data.getFlags()
& (Intent.FLAG_GRANT_READ_URI_PERMISSION
| Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
getActivity().getContentResolver().takePersistableUriPermission(treeUri, takeFlags);
}
And this is the code I used to copy files to SD card.
public static boolean copy(File copy, String directory, Context con) {
static FileInputStream inStream = null;
static OutputStream outStream = null;
DocumentFile dir= getDocumentFileIfAllowedToWrite(new File(directory), con);
String mime = mime(copy.toURI().toString());
DocumentFile copy1= dir.createFile(mime, copy.getName());
try {
inStream = new FileInputStream(copy);
outStream =
con.getContentResolver().openOutputStream(copy1.getUri());
byte[] buffer = new byte[16384];
int bytesRead;
while ((bytesRead = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inStream.close();
outStream.close();
return true;
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
The above code uses the following two methods.
getDocumentFileIfAllowedToWrite method which returns DocumentFile if allowed to write.
public static DocumentFile getDocumentFileIfAllowedToWrite(File file, Context con) {
List<UriPermission> permissionUris = con.getContentResolver().getPersistedUriPermissions();
for (UriPermission permissionUri : permissionUris) {
Uri treeUri = permissionUri.getUri();
DocumentFile rootDocFile = DocumentFile.fromTreeUri(con, treeUri);
String rootDocFilePath = FileUtil.getFullPathFromTreeUri(treeUri, con);
if (file.getAbsolutePath().startsWith(rootDocFilePath)) {
ArrayList<String> pathInRootDocParts = new ArrayList<String>();
while (!rootDocFilePath.equals(file.getAbsolutePath())) {
pathInRootDocParts.add(file.getName());
file = file.getParentFile();
}
DocumentFile docFile = null;
if (pathInRootDocParts.size() == 0) {
docFile = DocumentFile.fromTreeUri(con, rootDocFile.getUri());
} else {
for (int i = pathInRootDocParts.size() - 1; i >= 0; i--) {
if (docFile == null) {
docFile = rootDocFile.findFile(pathInRootDocParts.get(i));
} else {
docFile = docFile.findFile(pathInRootDocParts.get(i));
}
}
}
if (docFile != null && docFile.canWrite()) {
return docFile;
} else {
return null;
}
}
}
return null;
}
And mime method which returns the mime type of the file.
public static String mime(String URI) {
static String type;
String extention = MimeTypeMap.getFileExtensionFromUrl(URI);
if (extention != null) {
type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extention);
}
return type;
}
I have tested the above code with Android Lollipop and Marshmallow.
EDIT: This is the link to the FileUtils class.
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();
}
}
});
How to copy and move large amount of .txt files in one folder to multiple different subfolders in Java, based on certain characters in their filename?
The answers to which you've linked are out of date. As of Java 1.7 (which came out in 2011), you should be copying files this way:
Path afile = Paths.get("C:\\Users\\Documents\\testblankfiles\\xxxxxxxxxxxxx2.txt");
Path bfile = Paths.get("C:\\Users\\Documents\\testblankfilesdest\\2012\\xxxxxxxxxxxxx2.txt");
Files.copy(afile, bfile);
And you should be moving files this way:
Path afile = Paths.get("C:\\folderA\\Afile.txt");
Files.move(afile,
Paths.get("C:\\folderB", afile.getFileName().toString()));
Notice that Files.move doesn't return a value because, in proper object-oriented fashion, it throws an IOException if the move fails, unlike the ancient File.renameTo method.
JB Nizet is correct about determining your destination folders: Use the charAt
(or substring
) method on the result of Path.getFileName().toString().
To go through all the files in a directory, use a DirectoryStream:
try (DirectoryStream<Path> dir = Files.newDirectoryStream(
Paths.get("C:\\Users\\Documents\\TestBlankFiles"))) {
for (Path file : dir) {
String name = file.getFileName().toString();
if (!Files.isDirectory(file) && name.length() >= 14) {
char yearDigit = name.charAt(13);
Path destDir = Paths.get(
"C:\\Users\\Documents\\TestBlankFiles\\201" + yearDigit);
Files.createDirectories(destDir);
Files.move(file, destDir.resolve(name));
}
}
}
How to delete a whole folder and content?
Let me tell you first thing you cannot delete the DCIM folder because it is a system folder. As you delete it manually on phone it will delete the contents of that folder, but not the DCIM folder. You can delete its contents by using the method below:
Updated as per comments
File dir = new File(Environment.getExternalStorageDirectory()+"Dir_name_here");
if (dir.isDirectory())
{
String[] children = dir.list();
for (int i = 0; i < children.length; i++)
{
new File(dir, children[i]).delete();
}
}
Is there a way with python to move files on windows by reading origin and destination directories from a conf file?
With some changes, I was able to fix your code and get it working on my computer.
- Use
strip()
to remove the Windows style newline at the end of line and extra white space. This assumes that while your directory names might contain spaces, they won't end or start with a space. - Instead of doing
chdir
tosource_path
, I open it in place. This allows me to use relative paths instead of exclusively absolute ones, and there's really no need to change the dir anyway. As a result, the files insource_path
are referred to viaos.path.join(source_path, f)
. - Put a try/except around
listdir
to handle the case where the directory does not exist. - Test that
dest_dir
exists and is a directory, to avoid various problems. - I tested this script and it works on my Windows 10 machine with Python 3.9.5 called from PowerShell. It works with one or multiple lines, and the paths can use
\\
or just\
.
import shutil
import os
import os.path
import datetime
from pathlib import Path
filepath = r'c:\temp\acc.conf.txt'
with open(filepath, "r") as fp:
for cnt, line in enumerate(fp):
print("Line {}: {}".format(cnt, line))
a,b = line.split('|')
source= Path(a.strip())
source1=os.path.join(source)
source_path = os.path.normpath(source1)
print(b)
dst= Path(b)
dst1=os.path.join(dst)
dest_path = os.path.normpath(dst1)
if not os.path.isdir(dest_path):
print(dest_path + " is not a directory, skipping.")
continue
try:
files = os.listdir(source_path)
except FileNotFoundError as e:
print(e)
continue
now = datetime.datetime.now()
run_time= now.strftime("%Y-%m-%d %H:%M:%S")
for f in files:
print(run_time + " - " + f + "- " + os.getcwd() + "- " + dest_path)
print(f)
print(dest_path)
shutil.move(os.path.join(source_path, f), dest_path)
Related Topics
Android API 21 Toolbar Padding
Android:Difference Between Invisible and Gone
Firebase Firestore Variable Name Changed
Android Edittext Delete(Backspace) Key Event
How to Return to a Parent Activity Correctly
How to Use Opencv in Using Gradle
How to Store(Bitmap Image) and Retrieve Image from SQLite Database in Android
How to Sign an Android APK File
Android - Listview Get Item View by Position
How to Set My App as the Default Sms App
Overriding the Home Button - How to Get Rid of the Choice
Change Screen Orientation Programmatically Using a Button
Android - Set Max Length of Logcat Messages
How to Open the "Front Camera" on the Android Platform
Android Background Music Service