How to rename a file on sdcard with Android application? - android

In my Android application, I want to rename the file name at runtime. How can I do it?
This is my code:
String[] command = {" mv", "sun moon.jpg"," sun_moon,jpg"};
try
{
Process process = Runtime.getRuntime().exec(command);
}
catch (IOException e)
{
Toast.makeText(this, ""+e, Toast.LENGTH_LONG).show();
}
I also used renameTo(File f) method but it does not work.

I would recommend using File.renameTo() rather than running the mv command, since I'm fairly sure the latter isn't supported..
Have you given your application permission to write to the SD Card?
You do this by adding the following to your AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
If it doesn't work once the permission is added check the device log for errors when you try to rename the file (either using the adb command or in the logcat view in Eclipse).
When accessing the SD Card you shouldn't hard-code the path but instead use the Environment.getExternalStorageDirectory() method to get the directory.
The following code works for me:
File sdcard = Environment.getExternalStorageDirectory();
File from = new File(sdcard,"from.txt");
File to = new File(sdcard,"to.txt");
from.renameTo(to);
and if you want to check the process, you can do like:
boolean renamed = from.renameTo(to);
if (renamed) {
Log.d("LOG","File renamed...");
}else {
Log.d("LOG","File not renamed...");
}

you can also explicitly give the full path without specifying directory...
File file = new File("Path of file which you want to rename");
File file2 = new File("new name for the file");
boolean success = file.renameTo(file2);

I tried adding permissions. Even though it did not work, adding File1.setWritable(true); enabled me to rename the file.
Below is my code snippet:
if(from.setWritable(true))
Log.d("InsertFragmentTwo ", "FileName==> Is Writable");
File two = new File(sdcard,""+imageCount+"."+s.substring((s.lastIndexOf(".")+1)));
if (from.renameTo(two)) {
Log.d("InsertFragmentTwo ", "New FileName==> " + temp);
imageCount++;
retrofitImageUpload(temp);
} else
Log.d("InsertFragmentTwo ", "File Renaming Failed");

public void selectFile() {
AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
pictureDialog.setTitle("Select Action");
String[] pictureDialogItems = {
"Select file from internal storage"};
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
choosePhotoFromGallary();
break;
}
}
});
pictureDialog.show();
}
public void choosePhotoFromGallary() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, GALLERY);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == this.RESULT_CANCELED) {
return;
}
if (requestCode == GALLERY) {
if (data != null) {
Uri contentURI = data.getData();
File dir = Environment.getExternalStorageDirectory();
if(dir.exists()){
File from = new File(dir, String.valueOf(GALLERY));
File to = new File(dir,"filerename.txt");
if(from.exists())
from.renameTo(to);
}
}
}
}

Related

How to access any file based on the path name in android 10+ devices

In devices below android 10 we can access any file like this::
File f = new File("storage/emulated/0/filename.txt");
But I want to do to same on android 10+ devices which are using something like scoped storage or mediastore class that I didn't understood in android studio I don't know exactly how to do it I want to access files any directories not only public directories like "Pictures" please help me
File f = new File("storage/emulated/0/file.jpg");
To get all the files of folder xyz (storage/emulated/0/xyz) below android 10:
File xyzFolder = new File(Environment.getExternalStorageDirectory() + File.separator + "xyz");
File[] allFiles = xyzFolder.listFiles();
But for android 10 and above either use declare MANAGE_EXTERNAL_STORAGE (not recommended if it's not some kind of file manager app) or you can use below method:
1). First take folder permission
uriMain = Uri.parse("content://com.android.externalstorage.documents/tree/primary%3AAndroid%2Fmedia/document/primary%3Axyz");
private final int REQUEST_CODE = 100;
List<Object> filesList = new ArrayList<>();
private void aboveQFolderPermission() {
try {
Intent createOpenDocumentTreeIntent = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
createOpenDocumentTreeIntent = ((StorageManager) getSystemService(STORAGE_SERVICE)).getPrimaryStorageVolume().createOpenDocumentTreeIntent();
}
assert createOpenDocumentTreeIntent != null;
String replace = createOpenDocumentTreeIntent.getParcelableExtra("android.provider.extra.INITIAL_URI").toString().replace("/root/", "/document/");
createOpenDocumentTreeIntent.putExtra("android.provider.extra.INITIAL_URI", Uri.parse(replace + "%3A" + "xyz"));
startActivityForResult(createOpenDocumentTreeIntent, REQUEST_CODE);
} catch (Exception e) {
e.printStackTrace()
}
}
Now in onActivityResult(),
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE) {
if (data != null) {
getContentResolver().takePersistableUriPermission(data.getData(), Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
//save shared preference to check whether app specific folder permission granted or not
sharedPreferences = getSharedPreferences("tree", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("treeUriString", String.valueOf(uriMain));
editor.apply();
new Thread(() -> {
getListAboveQ(uriMain);
handler. Post(() -> /*Some code here as per your need*/);
}).start();
}
}
}
2). Now get the List of files:
private void getListAboveQ(uriMain) {
ContentResolver contentResolver = getContext().getContentResolver();
Uri buildChildDocumentsUriUsingTree = DocumentsContract.buildChildDocumentsUriUsingTree(uriMain, DocumentsContract.getDocumentId(uriMain));
try (Cursor cursor = contentResolver.query(buildChildDocumentsUriUsingTree, new String[]{"document_id"}, null, null, null)) {
while (cursor.moveToNext()) {
filesList.add(DocumentsContract.buildDocumentUriUsingTree(uriMain, cursor.getString(0)));
}
} catch (Exception e) {
e.printStackTrace();
}
}
Edit:- You can use saved preferences like:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
sharedPreferences = getSharedPreferences("tree", Context.MODE_PRIVATE);
String uriString = sharedPreferences.getString("treeUriString", "");
if (uriString.matches("")) {
//ask for folder permission
aboveQFolderPermission()
} else {
//Permission is already granted
//TODO: Whatever you want
}
}
You'll need to request MANAGE_EXTERNAL_STORAGE permission. With that permission, you can access shared storage files with the File API.
Reference:
https://developer.android.com/training/data-storage/manage-all-files#all-files-access

Android 11 scooped storage manage_external_storage permission is not accepted by google play console

my app is working fine below the 10 version but android 11 and higher versions do not support external storage. my picker is not picking any document file. but after giving manage_external_storage permission in manifest google play store did not approve my app. please help if you know any alternate solution for all file access permission.
Try like below. Create global variable as needed or refactor as per your need. This is tested upto Android 11.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
private void OpenCamera() {
try {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photoFile = null;
try {
photoFile = createFile();
} catch (Exception ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(getActivity().getApplicationContext(), getActivity().getApplicationContext().getPackageName() + ".fileprovider", photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, 3);
}
// }
} catch (Exception e) {
}
}
private File createFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName, /* prefix */".jpg", /* suffix */storageDir /* directory */);
// Save a file: path for use with ACTION_VIEW intents
ImageLoc = image.getAbsolutePath();
return image;
}
// Open Gallery
private void OpenGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image"), 1);
}
// onActivityResult handles gallery pics, camera pics and pdf.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if (resultCode == Activity.RESULT_OK) {
if (data.getData() != null) {
try {
Uri imageUri = data.getData();
File file = new File(Path_from_Uri.getPath(getActivity(), imageUri));
} catch (Exception e) {
Toast.makeText(getActivity(), "Please Select Image from Gallery", Toast.LENGTH_LONG).show();
}
}
}
} else if (requestCode == 3) {
try {
File file = new File(ImageLoc);
} catch (Exception e) {
Log.d("TAG", e.toString());
}
}
}

android Get file name and path from Download directory

I'm trying to copy a file from download folder to another directory.
i used this code to get the file path
int PICKFILE_RESULT_CODE=1;
Intent chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
chooseFile.setType("*/*");
chooseFile = Intent.createChooser(chooseFile, "Choose a file");
startActivityForResult( chooseFile,PICKFILE_RESULT_CODE);
I also used
#Override
public void onActivityResult(int requestCode, int resultCode,
Intent returnIntent) {
// If the selection didn't work
if (resultCode != RESULT_OK) {
// Exit without doing anything else
return;
} else {
returnUri = returnIntent.getData();
String src = returnUri.getPath();
Toast.makeText(this, src, Toast.LENGTH_SHORT).show();
}
}
The code works fine if the file is outside the download directory, when in it the path which i get is in the form of number not the actual name of the file like:
/document/2399
this gives an error of file not found
while the path from the root is:
/storage/emulated/0/myDB.db3
this works fine
pls help me to fix this
The code works fine if the file is outside the download directory
No, it does not. It works fine if the scheme of the Uri happens to be file. Most of the time, it will be content.
I'm trying to copy a file from download folder to another directory.
Use openInputStream() on a ContentResolver to get an InputStream on the content identified by the Uri. This works for both file and content schemes. Then, use standard Java I/O to copy the content from the InputStream to your desired location.
Here is the new code:
int PICKFILE_RESULT_CODE=1;
Intent chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
chooseFile.setType("*/*");
chooseFile = Intent.createChooser(chooseFile, "Choose a file");
startActivityForResult( chooseFile,PICKFILE_RESULT_CODE);
And used:
#Override
public void onActivityResult(int requestCode, int resultCode,
Intent returnIntent) {
InputStream is = null;
// If the selection didn't work
if (resultCode != RESULT_OK) {
// Exit without doing anything else
return;
} else {
// Get the file's content URI from the incoming Intent
Uri returnUri = returnIntent.getData();
try {
is = getContentResolver().openInputStream(returnUri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
BackUpHelper.importDB(is);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void importDB(InputStream is) throws IOException {
OutputStream os = null;
try {
String currentDBPath = DataBaseHelper2.DB_PATH+DataBaseHelper2.DB_NAME;
File outPut = new File(currentDBPath);
os = new FileOutputStream(outPut);
byte[] buffer = new byte[1024];
while (is.read(buffer) > 0) {
os.write(buffer);
}
Toast.makeText(context, R.string.export_successful,
Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(context, R.string.export_failed, Toast.LENGTH_SHORT)
.show();
}finally {
os.flush();
os.close();
is.close();
}
}

How to select folder in android?

Hi there is a way to select folder where user want to save file in android . I check out http://code.google.com/p/android-file-dialog/
it has functionality to select file but i want to select folder , please provide me usable link or examples.
How about using OI File Manager? This App has the following Intents: PICK_FILE, PICK_DIRECTORY.
There is even sample code on the page for using the Intents.
I used the same source in my app (pretty sure), and there is a block of code:
protected void onListItemClick(ListView l, View v, int position, long id) {
if (file.isDirectory()) {
selectButton.setEnabled(false);
if (file.canRead()) {
lastPositions.put(currentPath, position);
getDir(path.get(position));
} else {
new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle(
"[" + file.getName() + "] "
+ getText(R.string.cant_read_folder))
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
}
}).show();
}
} else {
selectedFile = file;
v.setSelected(true);
selectButton.setEnabled(true);
}
}
You just have to edit how it handle's if (file.isDirectory()). I would recommend declaring a boolean value in your Activity which you change to true if the file is a directory and it is already false. Then if said value is true, then traverse the directory. Also when you change said value to true, you would need to call selectButton.setEnabled(true). This would be quite a bit less complicated than making your own code, I would say.
Check out this answer https://stackoverflow.com/a/28479561/779140
I am mentioned library author so don't hesitate to ask any questions.
I encountered the same issue and I end up using NoNonsense-FilePicker
Add to gradle file
compile 'com.nononsenseapps:filepicker:4.0.0'
Trigger file/folder/dir pick
try {
Utils.makeHepticFeedback(getActivity());
Intent selectDirectoyIntent = new Intent(getActivity(), FilePickerActivity.class);
selectDirectoyIntent.putExtra(FilePickerActivity.EXTRA_ALLOW_MULTIPLE, false);
selectDirectoyIntent.putExtra(FilePickerActivity.EXTRA_ALLOW_CREATE_DIR, true);
selectDirectoyIntent.putExtra(FilePickerActivity.EXTRA_MODE, FilePickerActivity.MODE_DIR);
selectDirectoyIntent.putExtra(FilePickerActivity.EXTRA_START_PATH, Environment.getExternalStorageDirectory().getPath());
startActivityForResult(selectDirectoyIntent, FILE_CODE);
} catch (Exception e) {
Log.e(LOG_TAG, "exception", e);
e.printStackTrace();
Toast.makeText(getActivity(), e.toString(), Toast.LENGTH_SHORT).show();
}
Handle Activity result to get selected file or files
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && requestCode == CHOOSE_IMAGE_REQUEST_CODE) {
Uri selectedImageUri = data.getData();
String selectedImagePath = getRealPathFromURI(selectedImageUri);
// NOW WE HAVE OUR WANTED STRING
if (selectedImagePath != null) {
System.out
.println("selectedImagePath is the right one for you!");
PreferenceHelper.getPreferenceHelperInstance().setString(getActivity(),
PreferenceHelper.PLAYER_BACKGROUND,
selectedImageUri.toString());
Glide.with(getActivity()).load(Uri.parse(
PreferenceHelper.getPreferenceHelperInstance().getString(getActivity(),
PreferenceHelper.PLAYER_BACKGROUND
, AppConstants.DEFAULT_BACKGROUND_URL))).
into((ImageView) ButterKnife.findById(getActivity(), R.id.play_back));
}
} else if (requestCode == FILE_CODE && resultCode == Activity.RESULT_OK) {
if (null != data && !data.getBooleanExtra(FilePickerActivity.EXTRA_ALLOW_MULTIPLE, false)) {
// The URI will now be something like content://PACKAGE-NAME/root/path/to/file
Uri uri = data.getData();
// A utility method is provided to transform the URI to a File object
File file = com.nononsenseapps.filepicker.Utils.getFileForUri(uri);
// If you want a URI which matches the old return value, you can do
Uri fileUri = Uri.fromFile(file);
// Do something with the result...
Snackbar.make(fileFormat, "Recording folder updated to" + fileUri.getPath() + " ¯\\_(ツ)_/¯ ", Snackbar.LENGTH_SHORT).show();
AppConfig.RECORDING_FOLDER = fileUri.getPath();
PreferenceHelper.getPreferenceHelperInstance().setString(getActivity(), PreferenceHelper.RECORDING_FOLDER, AppConfig.RECORDING_FOLDER);
setUpSettingValue();
} else {
// Handling multiple results is one extra step
ArrayList<String> paths = data.getStringArrayListExtra(FilePickerActivity.EXTRA_PATHS);
if (paths != null) {
for (String path : paths) {
Uri uri = Uri.parse(path);
// Do something with the URI
File file = com.nononsenseapps.filepicker.Utils.getFileForUri(uri);
// If you want a URI which matches the old return value, you can do
Uri fileUri = Uri.fromFile(file);
// Do something with the result...
Toast.makeText(getActivity(), "Selected dir" + fileUri.getPath(), Toast.LENGTH_SHORT).show();
}
}
}
}
}

Android file chooser [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I want to make a file uploader. And I hence I need a file chooser but I don't want to write this by myself. I find OI file manager and I think it suits me.
But how can I force user to install OI file manager?
If I cannot , is there a better way to include a file manager in my app?
Thx
EDIT (02 Jan 2012):
I created a small open source Android Library Project that streamlines this process, while also providing a built-in file explorer (in case the user does not have one present). It's extremely simple to use, requiring only a few lines of code.
You can find it at GitHub: aFileChooser.
ORIGINAL
If you want the user to be able to choose any file in the system, you will need to include your own file manager, or advise the user to download one. I believe the best you can do is look for "openable" content in an Intent.createChooser() like this:
private static final int FILE_SELECT_CODE = 0;
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"),
FILE_SELECT_CODE);
} catch (android.content.ActivityNotFoundException ex) {
// Potentially direct the user to the Market with a Dialog
Toast.makeText(this, "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
}
You would then listen for the selected file's Uri in onActivityResult() like so:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case FILE_SELECT_CODE:
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
Log.d(TAG, "File Uri: " + uri.toString());
// Get the path
String path = FileUtils.getPath(this, uri);
Log.d(TAG, "File Path: " + path);
// Get the file instance
// File file = new File(path);
// Initiate the upload
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
The getPath() method in my FileUtils.java is:
public static String getPath(Context context, Uri uri) throws URISyntaxException {
if ("content".equalsIgnoreCase(uri.getScheme())) {
String[] projection = { "_data" };
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow("_data");
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
} catch (Exception e) {
// Eat it
}
}
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
I used AndExplorer for this purpose and my solution is popup a dialog and then redirect on the market to install the misssing application:
My startCreation is trying to call external file/directory picker. If it is missing call show installResultMessage function.
private void startCreation(){
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PICK);
Uri startDir = Uri.fromFile(new File("/sdcard"));
intent.setDataAndType(startDir,
"vnd.android.cursor.dir/lysesoft.andexplorer.file");
intent.putExtra("browser_filter_extension_whitelist", "*.csv");
intent.putExtra("explorer_title", getText(R.string.andex_file_selection_title));
intent.putExtra("browser_title_background_color",
getText(R.string.browser_title_background_color));
intent.putExtra("browser_title_foreground_color",
getText(R.string.browser_title_foreground_color));
intent.putExtra("browser_list_background_color",
getText(R.string.browser_list_background_color));
intent.putExtra("browser_list_fontscale", "120%");
intent.putExtra("browser_list_layout", "2");
try{
ApplicationInfo info = getPackageManager()
.getApplicationInfo("lysesoft.andexplorer", 0 );
startActivityForResult(intent, PICK_REQUEST_CODE);
} catch( PackageManager.NameNotFoundException e ){
showInstallResultMessage(R.string.error_install_andexplorer);
} catch (Exception e) {
Log.w(TAG, e.getMessage());
}
}
This methos is just pick up a dialog and if user wants install the external application from market
private void showInstallResultMessage(int msg_id) {
AlertDialog dialog = new AlertDialog.Builder(this).create();
dialog.setMessage(getText(msg_id));
dialog.setButton(getText(R.string.button_ok),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
dialog.setButton2(getText(R.string.button_install),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://details?id=lysesoft.andexplorer"));
startActivity(intent);
finish();
}
});
dialog.show();
}

Categories

Resources