SD 카드에서 파일을 삭제하는 방법은 무엇입니까?


131

이메일에 첨부 파일로 보낼 파일을 만들고 있습니다. 이제 이메일을 보낸 후 이미지를 삭제하고 싶습니다. 파일을 삭제하는 방법이 있습니까?

시도 myFile.delete();했지만 파일을 삭제하지 않았습니다.


Android에이 코드를 사용하고 있으므로 프로그래밍 언어는 일반적인 Android 방식으로 SD 카드에 액세스하는 Java입니다. 이메일을 보낸 후 화면으로 돌아 가면 onActivityResult메소드 에서 파일을 삭제하고 있습니다 Intent.


사용중인 언어, SD 카드에 액세스하는 방법 등과 같은 문제에 대한 자세한 정보를 제공해야합니다.
— Amok

디스크 변경 사항을 비우고 있습니까?
— Charles Ma

10
@Amuck 나는 그가 지정하지 않았기 때문에 Java를 사용한다고 가정하는 것이 안전하다고 생각합니다.
— Jeremy Logan

당신이 나에게 묻는다면 매우 의심스러운 소리 ...
— Studocwho

답변:


359
File file = new File(selectedFilePath);
boolean deleted = file.delete();

여기서 selectedFilePath는 삭제하려는 파일의 경로입니다 (예 :

/sdcard/YourCustomDirectory/ExampleFile.mp3


난 당신이 모든 내부 childs.See에게 .. 내 대답은 아래 삭제해야 .. 내부 아이들이 삭제되지 않습니다 생각
— 자르 E Ahmer

2
불행히도 이것은 Android 4.4 이상에서는 작동하지 않습니다. 아래 답변을 참조하십시오.
— stevo.mit

나는 이것이 많은 사람들에게 어떻게 작용했는지 이해하지 못한다. Android Studio에서 "삭제됨"이 회색으로 나타납니다.
— TheOnlyAnil

그래, 나는 작동하지 않는 "file : /// storage / ..."와 같은 경로를 보내고 있었다
— Jemshit Iskenderov

1
@ stevo.mit 솔루션을 찾았습니까? 또한 동일한 문제에 직면하여 Android 4.4 이상에서 sdcard에서 파일을 삭제할 수 없습니다. 그러나 동일한 코드가 4.3 /에서 작동
— hasnain_ahmad

79

또한> 1.6 SDK를 사용하는 경우 권한을 부여해야합니다

uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"

의 AndroidManifest.xml파일


하지만위한 이동식 SD 카드 저장 당신은 또한 필요ContentResolver
— USER25

35

Android 4.4 이상 변경

앱이되어 허용되지 않습니다 에 쓰기 (..., 수정, 삭제) 에 외부 저장 장치 를 제외하고 자신에 대한 패키지 별의 디렉토리.

안드로이드 문서에 따르면 :

"앱은 합성 된 권한에 의해 허용되는 패키지 별 디렉토리를 제외하고 보조 외부 저장 장치에 쓸 수 없어야합니다."

그러나 불쾌한 해결 방법 이 있습니다 (아래 코드 참조) . Samsung Galaxy S4에서 테스트되었지만이 수정 사항이 모든 장치에서 작동하지는 않습니다. 또한 이 해결 방법은 향후 버전의 Android 에서 사용할 수 있다고 생각하지 않습니다 .

(4.4+) 외부 저장소 권한 변경을 설명 하는 훌륭한 기사가 있습니다 .

당신이 읽을 수 있습니다 여기에 해결 방법에 대한 자세한 . 해결 방법 소스 코드는 이 사이트에서 제공 됩니다.

public class MediaFileFunctions 
{
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static boolean deleteViaContentProvider(Context context, String fullname) 
    { 
      Uri uri=getFileUri(context,fullname); 

      if (uri==null) 
      {
         return false;
      }

      try 
      { 
         ContentResolver resolver=context.getContentResolver(); 

         // change type to image, otherwise nothing will be deleted 
         ContentValues contentValues = new ContentValues(); 
         int media_type = 1; 
         contentValues.put("media_type", media_type); 
         resolver.update(uri, contentValues, null, null); 

         return resolver.delete(uri, null, null) > 0; 
      } 
      catch (Throwable e) 
      { 
         return false; 
      } 
   }

   @TargetApi(Build.VERSION_CODES.HONEYCOMB)
   private static Uri getFileUri(Context context, String fullname) 
   {
      // Note: check outside this class whether the OS version is >= 11 
      Uri uri = null; 
      Cursor cursor = null; 
      ContentResolver contentResolver = null;

      try
      { 
         contentResolver=context.getContentResolver(); 
         if (contentResolver == null)
            return null;

         uri=MediaStore.Files.getContentUri("external"); 
         String[] projection = new String[2]; 
         projection[0] = "_id"; 
         projection[1] = "_data"; 
         String selection = "_data = ? ";    // this avoids SQL injection 
         String[] selectionParams = new String[1]; 
         selectionParams[0] = fullname; 
         String sortOrder = "_id"; 
         cursor=contentResolver.query(uri, projection, selection, selectionParams, sortOrder); 

         if (cursor!=null) 
         { 
            try 
            { 
               if (cursor.getCount() > 0) // file present! 
               {   
                  cursor.moveToFirst(); 
                  int dataColumn=cursor.getColumnIndex("_data"); 
                  String s = cursor.getString(dataColumn); 
                  if (!s.equals(fullname)) 
                     return null; 
                  int idColumn = cursor.getColumnIndex("_id"); 
                  long id = cursor.getLong(idColumn); 
                  uri= MediaStore.Files.getContentUri("external",id); 
               } 
               else // file isn't in the media database! 
               {   
                  ContentValues contentValues=new ContentValues(); 
                  contentValues.put("_data",fullname); 
                  uri = MediaStore.Files.getContentUri("external"); 
                  uri = contentResolver.insert(uri,contentValues); 
               } 
            } 
            catch (Throwable e) 
            { 
               uri = null; 
            }
            finally
            {
                cursor.close();
            }
         } 
      } 
      catch (Throwable e) 
      { 
         uri=null; 
      } 
      return uri; 
   } 
}

1
note3에서는 작동하지 않습니다. "MediaProvider : /mnt/extSdCard/test.zip을 삭제할 수 없습니다"오류가 발생했습니다
— iscariot

2
4.4.4에 루트가없는 Moto X가 있고 / sdcard / mydirectory에 쓰는 데 문제가 없습니다
— Rob

"안타깝게도 최신 버전의 Kitkat에서는 더 이상 작동하지 않으며 모두 잠겨 있습니다." "ghisler (저자)"의 저자에서 인용
— HendraWD

안드로이드는 점점 더 문을 닫고있다. iOS의 추악한 사본으로 끝납니다!
— Phantômaxx

이것은 나에게 실패합니다 (Android 7.1). 그것은 항상 false파일을 반환 하고 삭제하지 않습니다 :-(
— Spikatrix

18

Android 컨텍스트에는 다음과 같은 방법이 있습니다.

public abstract boolean deleteFile (String name)

나는 이것이 위에 나열된 올바른 앱 선점으로 원하는 것을 할 것이라고 믿습니다.


3
이것이 정답이어야합니다. context.deleteFile(filename);
— Lisandro

11

파일의 모든 자식을 재귀 적으로 삭제합니다 ...

public static void DeleteRecursive(File fileOrDirectory) {
    if (fileOrDirectory.isDirectory()) {
        for (File child : fileOrDirectory.listFiles()) {
            DeleteRecursive(child);
        }
    }

    fileOrDirectory.delete();
}

9

이것은 나를 위해 작동합니다 : (갤러리에서 이미지 삭제)

File file = new File(photoPath);
file.delete();

context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(photoPath))));

2
context.sendBroadcast ()는 무엇을합니까?
— Megaetron

기본적으로이 의도와 일치하는 모든 수신자에게 의도 (작업 수행)를 전송 / 브로드 캐스트합니다. 링크
— Jiyeh

6
 public static boolean deleteDirectory(File path) {
    // TODO Auto-generated method stub
    if( path.exists() ) {
        File[] files = path.listFiles();
        for(int i=0; i<files.length; i++) {
            if(files[i].isDirectory()) {
                deleteDirectory(files[i]);
            }
            else {
                files[i].delete();
            }
        }
    }
    return(path.delete());
 }

이 코드는 당신을 도울 것입니다. 그리고 안드로이드 매니페스트에서 수정 권한을 얻어야합니다 ..

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

다음과 같은 경우 files []는 null 일 수 있습니다.file.exists:true file.isDirectory:true file.canRead:false file.canWrite:false
— ilw

일부 안드로이드 폰은 SD 카드에 대한 쓰기 액세스를 제한한다는 것을 완전히 알지 못합니다.


1

죄송합니다. 사이트 확인으로 인해 코드에 실수가 있습니다.

String myFile = "/Name Folder/File.jpg";  

String myPath = Environment.getExternalStorageDirectory()+myFile;  

File f = new File(myPath);
Boolean deleted = f.delete();

분명하다고 생각합니다 ... 먼저 파일 위치를 알아야합니다. 둘째, Environment.getExternalStorageDirectory()앱 디렉토리를 얻는 방법입니다. 마지막으로 파일을 처리하는 클래스 File ...


1

4.4에서 실행되는 응용 프로그램과 비슷한 문제가있었습니다. 내가 한 것은 일종의 해킹이었습니다.

파일 이름을 바꾸고 응용 프로그램에서 무시했습니다.

즉.

File sdcard = Environment.getExternalStorageDirectory();
                File from = new File(sdcard,"/ecatAgent/"+fileV);
                File to = new File(sdcard,"/ecatAgent/"+"Delete");
                from.renameTo(to);

0

이것은 나를 위해 일했습니다.

String myFile = "/Name Folder/File.jpg";  

String my_Path = Environment.getExternalStorageDirectory()+myFile;  

File f = new File(my_Path);
Boolean deleted = f.delete();

0
private boolean deleteFromExternalStorage(File file) {
                        String fileName = "/Music/";
                        String myPath= Environment.getExternalStorageDirectory().getAbsolutePath() + fileName;

                        file = new File(myPath);
                        System.out.println("fullPath - " + myPath);
                            if (file.exists() && file.canRead()) {
                                System.out.println(" Test - ");
                                file.delete();
                                return false; // File exists
                            }
                            System.out.println(" Test2 - ");
                            return true; // File not exists
                    }

코드에 대한 설명을 제공해야합니다! :)
— Sanket Makani

getExternalStorageDirectory 파일을 읽고 "/ Music /"을 추가하십시오. 이것은 나의 경로입니다-> mypath = / storage / sdcard / Music /. 파일이 존재하거나 존재하지 않는지 확인한 후 읽으십시오. 존재하는 경우 삭제하십시오. 이 디렉토리 음악의 모든 목록의 음악을 삭제할 수 있습니다
— 램 응 우옌 투안

답변에 동일하게 추가하십시오! :)
— Sanket Makani

0

다음과 같이 파일을 삭제할 수 있습니다.

File file = new File("your sdcard path is here which you want to delete");
file.delete();
if (file.exists()){
  file.getCanonicalFile().delete();
  if (file.exists()){
    deleteFile(file.getName());
  }
}

-1
File filedel = new File("/storage/sdcard0/Baahubali.mp3");
boolean deleted1 = filedel.delete();

또는 이것을 시도하십시오 :

String del="/storage/sdcard0/Baahubali.mp3";
File filedel2 = new File(del);
boolean deleted1 = filedel2.delete();

1
두 예제는 거의 동일합니다. 또한, 가장 높은 투표 응답은 이것을 정확하게 지시합니다. 이 답변이 질문을 더 추가하는 것을 볼 수 없습니다. 또한 Android Kitkat 이후 IIRC의 SD 카드와 같은 외부 저장소에있는 파일의 경우 작동하지 않습니다.
— Spikatrix
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.