SD 카드에서 파일을 삭제하는 방법은 무엇입니까? 삭제하는 방법이 있습니까? 시도 myFile.delete();했지만

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

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


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



답변

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

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

/sdcard/YourCustomDirectory/ExampleFile.mp3


답변

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

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

AndroidManifest.xml파일


답변

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

답변

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

public abstract boolean deleteFile (String name)

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


답변

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

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

    fileOrDirectory.delete();
}

답변

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

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

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

답변

 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"/>