2013-08-04 2 views
1

나는 android app에서 일하고 있는데, 파일의 이름을 바꾸고 싶다.내 파일의 이름을 변경하지 않는 이유는 무엇입니까?

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

솔루션 큰 감사를 @SD에 (주석 참조)

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

이 문제의 본질은 무엇이며 그것을 던져 않습니다 추가 할 수있는 권한이

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

이 게시물 "입니다..? 예외가 발생하거나 그냥 false를 반환합니까? –

+0

'f.getAbsolutePath()'를'f.getParent()'로 대체하십시오. –

+0

매력처럼 작동했습니다! 고마워요! – user2351234

답변

1

나는 문제가 생각 :

File f = adapter.getItem(i); 

가 부여 문제는 이름을 변경되지 않는 것입니다 File f을 사용하십시오. 과 같이 f의 cooresponds라고 말하면됩니다. 그런 다음을 수행하십시오 user2351234/Desktop/helloworld : 말한다

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

어디 file에 cooresponds하려면 File file 할 수 있습니다. 다음으로, 전화 : 시도

f.renameTo(file) 

user2351234/Desktop 존재하기 user2351234/Desktop/helloworld 위해서는 있기 때문에 이해가되지 않습니다 user2351234/Desktop/helloworld에, f 이름을 바꾸려면, user2351234/Desktop이 존재해야하지만, 작업의 미덕는 것 더이상 존재하지 않는다.

내 가설 은 이유하지 수 있지만, Why doesn't File.renameTo(…) create sub-directories of destination?에서, 분명히 renameTo것이다 반환 false 하위 디렉토리가 존재하지 않는 경우. 그냥 파일의 이름을 변경하려면

, 이렇게 :

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

편집 :
내 제안 된 솔루션을 작동해야하지만 경우에 당신의 방법하지 않는 이유에 대한 내 가설 작업이 잘못되었습니다. 이걸보고 싶을 수도 있습니다. answerReliable File.renameTo() alternative on Windows?

0

사용이 코드

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