Programming

SD 카드에서 파일을 삭제하는 방법?

procodes 2020. 7. 1. 22:14
반응형

SD 카드에서 파일을 삭제하는 방법?


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

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

이 시도.

File file = new File(FilePath);
FileUtils.deleteDirectory(file);

Apache Commons에서


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

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

String myPath = Environment.getExternalStorageDirectory()+myFile;  

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

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


I had a similar issue with an application running on 4.4. What I did was sort of a hack.

I renamed the files and ignored them in my application.

ie.

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

This worked for me.

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

String my_Path = Environment.getExternalStorageDirectory()+myFile;  

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

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
                    }

You can delete a file as follow:

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

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

Or, Try This:

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

참고URL : https://stackoverflow.com/questions/1248292/how-to-delete-a-file-from-sd-card

반응형