Невозможно удалить файлы с SDCard, используя функции удаления - PullRequest
0 голосов
/ 02 марта 2012

В моем приложении я сохраняю таблицу как изображение.Пользователь может удалить файл (изображение) после его открытия. Я использую следующий код для открытия изображения, когда пользователь нажимает «Открыть»:

File directory=new  File(extStorageDirectory,File.separator+"myDirectory"+File.separator);
File fileInDirectory=new File(directory, fileName); 

//I save the opened file's path n "filePath"
filePath=fileInDirectory.getAbsolutePath();
Bitmap bitmap = BitmapFactory.decodeFile(fileInDirectory.getAbsolutePath());  
ImageView ivv=(ImageView) findViewById(R.id.imageView);
ivv.setImageBitmap(bitmap);

//I enable the delete button
deleteFile.setEnabled(true);

Файл открывается без каких-либо проблем.И когда пользователь нажимает «Удалить», я делаю следующее:

  //I create a file using the filePath I saved earlier
  File file=new File(filePath);
  file.delete();                      

Но он не удаляет файл из SDCard.Я подтвердил, и filePath правильный.Я также попробовал функцию deleteFile (String):

 deleteFile(fileNeme);
 //fileName is the name of my file that I save earlier and I've verified it by printing it and there is no problem. 

Я поместил

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

в мой файл манифеста.Поэтому я не думаю, что это проблема прав, так как я могу писать и читать с SDCard.

Есть ли способ сделать это?сохраните файл.

this.save.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
AlertDialog.Builder alert=new AlertDialog.Builder(LensCalculator.this);
alert.setTitle("Save");
alert.setMessage("Enter file name");

final EditText input=new EditText(MyActivity.this);
alert.setView(input);

alert.setPositiveButton("OK", new DialogInterface.OnClickListener(){
    @Override
    public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
    TableView table=(TableView) findViewById(R.id.tableId);
    table.setDrawingCacheEnabled(true);
    Bitmap b=table.getDrawingCache();
    Canvas canvas=new Canvas(b);
    canvas.drawBitmap(b, 0f, 175f, null);
    OutputStream outStream = null;
    String fileName=input.getText().toString();
    File directory =new File(extStorageDirectory+File.separator+"myDirectory"+File.separator);
    if(!directory.mkdir())
           directory.mkdir();
    File file = new File(directory, fileName);
    try {
        outStream = new FileOutputStream(file);
        b.compress(Bitmap.CompressFormat.PNG, 100, outStream);
        FileOutputStream fOut=openFileOutput("public.dat", Context.MODE_PRIVATE|Context.MODE_APPEND);
        OutputStreamWriter osw=new OutputStreamWriter(fOut);
        osw.write(fileName+"\n");

        osw.close();
        fOut.close();
        outStream.close();
        table.destroyDrawingCache();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
            e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
            e.printStackTrace();
    }
}
});

Ответы [ 2 ]

0 голосов
/ 02 марта 2012

Если путь правильный и у вас есть разрешение и файл не открыт, он должен работать. Это загадочная ситуация. Есть ли у вас какие-либо исключения? Убедитесь, что у вас нет ничего подобного:

catch(Exception e) { 
 // Do nothing
}

А это удаленная возможность, но в любом случае. Как проверить, что файл удален? Помните, что при подключении телефона к компьютеру и при установке SD-карты ваше приложение не сможет получить к нему доступ (поэтому не сможет удалить файл).

Еще одна удаленная возможность ... Попробуйте добавить:

/*...*/
ivv.setImageBitmap(bitmap);
bitmap.recycle();
bitmap = null;

EDIT

Я не понимаю, зачем вам такой сложный код, это может быть намного проще:

File file = new File(directory, fileName);
try {
    outStream = new FileOutputStream(file);
    b.compress(Bitmap.CompressFormat.PNG, 100, outStream);
    FileOutputStream fOut=openFileOutput(fileName, Context.MODE_PRIVATE|Context.MODE_APPEND);
    OutputStreamWriter osw=new OutputStreamWriter(fOut);
    osw.write(fileName+"\n");

    osw.close();
    fOut.close();
    outStream.close();
    table.destroyDrawingCache();
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
        e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
        e.printStackTrace();
}

Как это:

FileOutputStream out = null;
try {
       out = new FileOutputStream(directory + fileName);
       bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (Exception e) {
       e.printStackTrace();
} finally {
       try {
           if(out != null) {
               out.close();
           }
       }
       catch (Exception e) {
           e.printStackTrace();
       }
}
0 голосов
/ 02 марта 2012

Просто попробуйте: yourFile.delete();

...