user2351234
user2351234

Reputation: 975

Why won't my file rename itself?

I am working on an android app and I want to rename a file. The problem is that it is not renaming:

 File f = adapter.getItem(i);
 File file = new File(f.getAbsolutePath(), "helloworld");
 if (f.renameTo(file)) {
 Toast.makeText(getActivity(), "done", Toast.LENGTH_LONG).show();
 }

Solution BIg Thanks to @S.D.(see comments)

File f = adapter.getItem(i);
     File file = new File(f.getParent(), "helloworld");
     if (f.renameTo(file)) {
     Toast.makeText(getActivity(), "done", Toast.LENGTH_LONG).show();
     }

Upvotes: 1

Views: 378

Answers (3)

Steve P.
Steve P.

Reputation: 14699

I think the issue is that:

File f = adapter.getItem(i);

Gives use some File f, say where f cooresponds to say: user2351234/Desktop. Then, you do:

 File file = new File(f.getAbsolutePath(), "helloworld");

Which says to make a File file, where file cooresponds to: user2351234/Desktop/helloworld. Next, you call:

f.renameTo(file)

which attempts to rename f, user2351234/Desktop to user2351234/Desktop/helloworld, which doesn't make sense since in order for user2351234/Desktop/helloworld to exist, user2351234/Desktop would have to exist, but by virtue of the operation it would no longer exist.

My hypothesis may not be the reason why, but from Why doesn't File.renameTo(…) create sub-directories of destination?, apparently renameTo will return false if the sub-directory does not exist.

If you want to just change the name of the file, do this:

File f = adapter.getItem(i);
String file = f.getAbsolutePath() + "helloworld";
f = new File(file);

EDIT:
My proposed solution should work, but if my hypothesis about why your way does not work is incorrect, you may want to see this answer from Reliable File.renameTo() alternative on Windows?

Upvotes: 1

Prakhar
Prakhar

Reputation: 2310

use this code.

File sdcard = Environment.getExternalStorageDirectory()+ "/nameoffile.ext" ;
File from = new File(sdcard,"originalname.ext");
File to = new File(sdcard,"newname.ext");
from.renameTo(to);

Upvotes: 0

lordoku
lordoku

Reputation: 1112

Question 1: Do you see an exception or does it return false?

Question 2: Did you give permission for the app to write to the SD card? (I'm assuming that's where this file lies). The permission to add is"

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

This posting: How to rename a file on sdcard with Android application? seems to answer a similar question.

Upvotes: 0

Related Questions