2010-05-24 4 views
11

내 Android 애플리케이션에서 런타임에 파일 이름의 이름을 바꾸고 싶습니다. 내가 어떻게 해?안드로이드 응용 프로그램으로 sdcard에서 파일의 이름을 바꾸는 방법은 무엇입니까?

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(); 
} 

나는 또한 renameTo (파일 C) 방법을 사용하지만이 작동하지 않습니다

내 코드입니다.

+0

방문일 : http://stackoverflow.com/questions/9065514/move-rename- 아래

내 코드입니다 파일 - 인 - sd - 카드 –

+1

사람들이 당신을 도울 수 있기를 원하면 대답을 받아 들여야합니다. FY12 – Gattsu

답변

81

나는 후자는 지원되지 않습니다 꽤 확신하기 때문에 내가

당신이 당신의 application permission to write to the SD Card을 봤나 .. File.renameTo()를 사용하는 대신 mv 명령을 실행하는 것이 좋습니다?

당신은 adding the following to your AndroidManifest.xml하여이 작업을 수행 : 권한 당신이 adb 명령을 사용하여 또는에서 중 (파일 이름을 바꿀 때 오류 장치 로그를 확인 추가되면

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

가 작동하지 않는 경우 logcat 이클립스에서보기).

SD 카드에 액세스 할 때 경로를 하드 코딩하지 말고 대신 the Environment.getExternalStorageDirectory() 메서드를 사용하여 디렉토리를 가져와야합니다.

File sdcard = Environment.getExternalStorageDirectory(); 
File from = new File(sdcard,"from.txt"); 
File to = new File(sdcard,"to.txt"); 
from.renameTo(to); 

을하고이 과정을 확인하려는 경우처럼, 당신은 할 수 있습니다 :

다음 코드는 나를 위해 작동 당신이 명시 적으로 디렉토리를 지정하지 않고 전체 경로를 제공 할 수 있습니다

boolean renamed = from.renameTo(to); 

if (renamed) { 
    Log.d("LOG","File renamed..."); 
}else { 
    Log.d("LOG","File not renamed..."); 
} 
+0

지금 시도하십시오 파일 f1 = 새 파일 ("/ sdcard/sun moon.jpg"); 파일 f2 = 새 파일 ("/ sdcard/soon_moon.jpg"); \t { \t f1.renameTo (f2); \t} 캐치 (예외 E) { \t \t Toast.makeText (이 ","E +, Toast.LENGTH_LONG) .show(); \t \t} 및 권한 를 사용하는 <사용 - 권한 안드로이드 : 이름 = "android.permission.WRITE_EXTERNAL_STORAGE"/>의 AndroidManifest.xml에서 는 을 제기하지만 여전히 아무런 변화가 없다. – Addy

+0

logcaat에 오류가 없습니다. – Addy

+0

저에게 맞는 코드로 답변을 업데이트했습니다.당신이 그것을 실행할 때'renameTo()'는'true' 또는'false'를 리턴합니까? 'false'를 반환하면'f1.exists()'는 무엇을 반환합니까? –

5

...

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); 
0

사용 권한을 추가하려고 시도했습니다. 작동하지 않더라도 File1.setWritable(true);을 추가하면 파일의 이름을 바꿀 수 있습니다. [이 하나] [1] [1]

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"); 
관련 문제