How to rename a file? - android

A quick question, how do i rename a file?
File to = new File(f.getAbsolutePath(), etRenameStr.getText().toString() );
f.renameTo(to);
expl();
tried like that, but doesn't seem to work.
Thanks!

File dir = Environment.getExternalStorageDirectory();
if(dir.exist()){
File from = new File(dir,"from.mp4");
File to = new File(dir,"to.mp4");
if(from.exist())
from.renameTo(to);
}
http://developer.android.com/reference/java/io/File.html#renameTo%28java.io.File%29

I think getAbsolutePath() returns the full path including file name, that might be a problem here. Try getParent() instead and see if it works.

File rootDir = Environment.getExternalStorageDirectory();
File file = new File(rootDir + "/Files/"+fileName);
File file2 = new File("newname");
// Rename file (or directory)
boolean success = file.renameTo(file2);
if (!success) {
System.out.println("File was not successfully renamed");
}
This worked for me. please check once!!

Related

Deleted file reappers in the File browser

When downloading a pdf file using DownloadManager, I want to delete it if it already exists in Environment.DIRECTORY_DOWNLOADS.
I check if file exists and delete it using these code:
private boolean fileExists(String fileName) {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
fileName);
return file.exists();
}
private boolean removeFile(String fileName) {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
fileName);
return file.delete();
}
removeFile() says that file is deleted, by returning true, and when I look into File Browser only one file is showing up. But when I delete that file it reappers on top of old one. What's wrong?
if i'm not wrong the File file= new File(...) will be your problem.
Because you are using the File class constructor, which is creates a new file to the exact location (File class documentation is here documentation).
Try to give your removeFile(String)method a File type variable, that should do the trick (or use some File 'getting' method from the documentation).

File.mkdir() and mkdirs() are creating file instead of directory

I use the following code:
final File newFile = new File("/mnt/sdcard/test/");
newFile.mkdir(); // if I use mkdirs() result is the same
And it creates an empty file! Why?
You wouldn't use mkdirs() unless you wanted each of those folders in the structure to be created. Try not adding the extra slash on the end of your string and see if that works.
For example
final File newFile = new File("/mnt/sdcard/test");
newFile.mkdir();
When I need to ensure that all dirs for a file exist, but I have only filepath - i do
new File(FileName.substring(0,FileName.lastIndexOf("/"))).mkdirs();
First of all you shouldn't use a file path with "/mnt/sdcard/test", this may cause some problems with some android phones. Use instead:
public final static String APP_PATH_SD_CARD = "/Test";
String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath() + APP_PATH_SD_CARD;
It creates an empty file since you added the dash.
Now that you have your path use the following code:
try {
File dir = new File(fullPath);
if (!dir.exists()) {
dir.mkdirs();
}
}
catch(Exception e){
Log.w("creating file error", e.toString());
}
Try to use
String rootPath=Environment.getExternalStorageDirectory().getAbsolutePath()+"/test/";
File file=new File(rootPath);
if(!file.exists()){
file.mkdirs();
}

Check if file exists on SD card on Android

I want to check if a text file exists on the SD card. The file name is mytextfile.txt. Below is the code:
FileOutputStream fos = openFileOutput("sdcard/mytextfile.txt", MODE_WORLD_WRITEABLE);
How can I check whether this file exists?
This should do the trick, I've replaced the hard coded SDcard reference to the recommended API call getExternalCacheDir():
File file = new File(getExternalCacheDir(), "mytextfile.txt" );
if (file.exists()) {
//Do action
}
See this file System in android : Working with SDCard’s filesystem in Android
you just check
if(file.exists()){
//
}
*Using this you can check the file is present or not in sdcard *
File file = new File(sdcardpath+ "/" + filename);
if (file.exists())
{
}
You have to create a file, and set it to be the required file, and check if it exists.
String FILENAME="mytextfile.txt";
File fileToCheck = new File(getExternalCacheDirectory(), FILENAME);
if (fileToCheck.exists()) {
FileOutputStream fos = openFileOutput("sdcard/mytextfile.txt", MODE_WORLD_WRITEABLE);
}
Have Fun!
The FileOutputStream constructor will throw a FileNotFound exception if the specified file doesn't exist. See the Oracle documentation for more information.
Also, make sure you have permission to access the SD card.
check IF condition with Boolean type like
File file = new File(path+filename);
if (file.exists() == true)
{
//Do something
}

check that given file is present on this path or not in Android Filesystem?

How can we check the given file is present in Android Filesystem or not without using File inputstream.because I only want to check the existence of the file on the given path.
File myFile = new File("/path/to/file");
if (myFile.isFile()) {
...
}
If you have created a file using openFileOutput method then this works
File mFile = new File(getBaseContext().getFilesDir(),FileName);
if (mFile.exists() )
{
//File is Exits.
}
else
{
//File is not Exits.
}
hope this helps

Delete file from internal storage

I'm trying to delete images stored in internal storage. I've come up with this so far:
File dir = getFilesDir();
File file = new File(dir, id+".jpg");
boolean deleted = file.delete();
And this is from another question, which was answered with:
File dir = getFilesDir();
File file = new File(dir, "my_filename");
boolean deleted = file.delete();
My example always returns false. I can see the file fx 2930.jpg in DDMS in eclipse.
The getFilesDir() somehow didn't work.
Using a method, which returns the entire path and filename gave the desired result. Here is the code:
File file = new File(inputHandle.getImgPath(id));
boolean deleted = file.delete();
Have you tried Context.deleteFile() ?
Java
File file = new File(photoPath);
file.delete();
MediaScannerConnection.scanFile(context,
new String[]{file.toString()},
new String[]{file.getName()},null);
Kotlin
val file = File(photoPath)
file.delete()
MediaScannerConnection.scanFile(context, arrayOf(file.toString()),
arrayOf(file.getName()), null)
String dir = getFilesDir().getAbsolutePath();
File f0 = new File(dir, "myFile");
boolean d0 = f0.delete();
Log.w("Delete Check", "File deleted: " + dir + "/myFile " + d0);
The code File dir = getFilesDir(); doesn't work because this is a request for a File object.
You're trying to retrieve the String that declares the path to your directory, so you need to declare 'dir' as a String, and then request that the directory's absolute path in String form be returned by the constructor that has access to that information.
You can also use: file.getCanonicalFile().delete();
File file = new File(getFilePath(imageUri.getValue()));
boolean b = file.delete();
is not working in my case.
boolean b = file.delete(); // returns false
boolean b = file.getAbsolutePath.delete(); // returns false
always returns false.
The issue has been resolved by using the code below:
ContentResolver contentResolver = getContentResolver();
contentResolver.delete(uriDelete, null, null);
Have you tried getFilesDir().getAbsolutePath()?
Seems you fixed your problem by initializing the File object with a full path. I believe this would also do the trick.
> 2019-11-12 20:05:50.178 27764-27764/com.strba.myapplicationx I/File: /storage/emulated/0/Android/data/com.strba.myapplicationx/files/Readings/JPEG_20191112_200550_4444350520538787768.jpg//file when it was created
2019-11-12 20:05:58.801 27764-27764/com.strba.myapplicationx I/File: content://com.strba.myapplicationx.fileprovider/my_images/JPEG_20191112_200550_4444350520538787768.jpg //same file when trying to delete it
solution1:
Uri uriDelete=Uri.parse (adapter.getNoteAt (viewHolder.getAdapterPosition ()).getImageuri ());//getter getImageuri on my object from adapter that returns String with content uri
here I initialize Content resolver
and delete it with a passed parameter of that URI
ContentResolver contentResolver = getContentResolver ();
contentResolver.delete (uriDelete,null ,null );
solution2(my first solution-from head in this time I do know that ): content resolver exists...
String path = "/storage/emulated/0/Android/data/com.strba.myapplicationx/files/Readings/" +
adapter.getNoteAt (viewHolder.getAdapterPosition ()).getImageuri ().substring (58);
File file = new File (path);
if (file != null) {
file.delete ();
}

Categories

Resources