wudhw7283

Copy with SAF

Sep 28th, 2025
40
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 4.25 KB | Source Code | 0 0
  1. import android.net.Uri;
  2. import android.provider.DocumentsContract;
  3. import android.database.Cursor;
  4. import java.io.InputStream;
  5. import java.io.OutputStream;
  6. import java.io.File;
  7. import java.io.FileOutputStream;
  8. import java.util.regex.Pattern;
  9. import org.json.JSONArray;
  10. import org.json.JSONObject;
  11.  
  12. // === Inputs ===
  13. String treeStr   = "%uri_tree";   // SAF source tree
  14. String targetStr = "%target";     // must be /storage/... filesystem path
  15. String pattern   = "%pattern";    // e.g. /databases/*.db
  16.  
  17. // --- Extract subPath + file pattern ---
  18. String subPath = "";
  19. String filePattern = pattern;
  20.  
  21. int slashIdx = pattern.lastIndexOf("/");
  22. if (slashIdx != -1) {
  23.     subPath = pattern.substring(0, slashIdx);       // e.g. "/databases"
  24.     filePattern = pattern.substring(slashIdx + 1);  // e.g. "*.db"
  25.     if (subPath.startsWith("/")) subPath = subPath.substring(1);
  26. }
  27.  
  28. // Convert wildcard → regex
  29. String regex = filePattern.replace(".", "\\.").replace("*", ".*").replace("?", ".");
  30. Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
  31.  
  32. // --- Setup source tree ---
  33. Uri treeUri = Uri.parse(treeStr);
  34. String rootDocId = DocumentsContract.getTreeDocumentId(treeUri);
  35. Uri currentChildren = DocumentsContract.buildChildDocumentsUriUsingTree(treeUri, rootDocId);
  36.  
  37. // Walk into subPath if provided
  38. if (!subPath.isEmpty()) {
  39.     String[] parts = subPath.split("/");
  40.     for (String part : parts) {
  41.         Cursor c = context.getContentResolver().query(
  42.             currentChildren,
  43.             new String[] {
  44.                 DocumentsContract.Document.COLUMN_DOCUMENT_ID,
  45.                 DocumentsContract.Document.COLUMN_DISPLAY_NAME,
  46.                 DocumentsContract.Document.COLUMN_MIME_TYPE
  47.             },
  48.             null, null, null);
  49.  
  50.         boolean found = false;
  51.         if (c != null) {
  52.             while (c.moveToNext()) {
  53.                 String childId = c.getString(0);
  54.                 String name    = c.getString(1);
  55.                 String mime    = c.getString(2);
  56.  
  57.                 if (name != null && name.equals(part) &&
  58.                     DocumentsContract.Document.MIME_TYPE_DIR.equals(mime)) {
  59.                     currentChildren = DocumentsContract.buildChildDocumentsUriUsingTree(treeUri, childId);
  60.                     found = true;
  61.                     break;
  62.                 }
  63.             }
  64.             c.close();
  65.         }
  66.         if (!found) {
  67.             throw new IllegalArgumentException("Subfolder not found: " + part);
  68.         }
  69.     }
  70. }
  71.  
  72. // --- Prepare JSON result ---
  73. JSONArray result = new JSONArray();
  74.  
  75. // --- Query + match files ---
  76. Cursor cursor = context.getContentResolver().query(
  77.     currentChildren,
  78.     new String[] {
  79.         DocumentsContract.Document.COLUMN_DOCUMENT_ID,
  80.         DocumentsContract.Document.COLUMN_DISPLAY_NAME
  81.     },
  82.     null, null, null);
  83.  
  84. if (cursor != null) {
  85.     while (cursor.moveToNext()) {
  86.         String childId = cursor.getString(0);
  87.         String name    = cursor.getString(1);
  88.  
  89.         if (name != null && p.matcher(name).matches()) {
  90.             JSONObject item = new JSONObject();
  91.             item.put("name", name);
  92.             item.put("status", "matched");
  93.  
  94.             try {
  95.                 // Source stream
  96.                 Uri srcDocUri = DocumentsContract.buildDocumentUriUsingTree(treeUri, childId);
  97.                 InputStream in = context.getContentResolver().openInputStream(srcDocUri);
  98.  
  99.                 // Destination: filesystem file
  100.                 File destFile = new File(targetStr, name);
  101.                 if (destFile.exists()) destFile.delete(); // overwrite
  102.                 OutputStream out = new FileOutputStream(destFile);
  103.  
  104.                 byte[] buffer = new byte[8192];
  105.                 int len;
  106.                 while ((len = in.read(buffer)) != -1) {
  107.                     out.write(buffer, 0, len);
  108.                 }
  109.  
  110.                 in.close();
  111.                 out.close();
  112.  
  113.                 item.put("copied", true);
  114.                 item.put("targetPath", destFile.getAbsolutePath());
  115.             } catch (Exception e) {
  116.                 item.put("copied", false);
  117.                 item.put("error", e.toString());
  118.             }
  119.  
  120.             result.put(item);
  121.         }
  122.     }
  123.     cursor.close();
  124. }
  125.  
  126. return result.toString();
  127.  
Advertisement
Add Comment
Please, Sign In to add comment