android-如何在替换文件之前从内存中删除文件

android-如何在替换文件之前从内存中删除文件,第1张

概述我想在运行时删除内部文件.当我从外部服务器下载文件时,文件的旧版本(具有相同的名称)将被替换,但是我无法读取它.我认为我需要在下载新版本之前删除以前的文件.这是到目前为止我尝试过的一个示例:try{FileOutputStreamfos=getApplicationContext().openFileOutput("myte

我想在运行时删除内部文件.当我从外部服务器下载文件时,文件的旧版本(具有相同的名称)将被替换,但是我无法读取它.我认为我需要在下载新版本之前删除以前的文件.这是到目前为止我尝试过的一个示例:

try {    fileOutputStream fos = getApplicationContext().openfileOutput("mytext.txt", Context.MODE_PRIVATE);    fos.write(getStringFromfile(pictosfile.getabsolutePath()).getBytes());    Log.e("mytextfile",""+getStringFromfile(pictosfile.getabsolutePath()));    progressDialog.cancel();    fos.close();} catch (IOException e) {    e.printstacktrace();} catch (Exception e) {    e.printstacktrace();}

这使我可以将文件保存到内存中,但是我不确定在编写新版本之前如何删除以前的文件.

解决方法:

如果需要确保文件被覆盖,即在保存新版本之前删除旧副本,则可以对文件对象使用exist()方法.这是一个示例,显示了如何在嵌套目录中写入具有相同名称的新文件之前删除图像文件的旧版本:

// Here TARGET_BASE_PATH is the path to the base folder// where the file is to be stored// 1 - Check that the file exists and delete if it doesfile myDir = new file(TARGET_BASE_PATH);// Create the nested directory structure if it does not exist (first write)if(!myDir.exists())    myDir.mkdirs();String fname = "my_new_image.jpg";file file = new file(myDir,fname);// Delete the prevIoUs versions of the file if it existsif(file.exists())    file.delete();String filename = file.toString();bufferedoutputstream bos = null;// 2 - Write the new version of the file to the same locationtry{    bos = new bufferedoutputstream(new fileOutputStream(filename));    Bitmap bmp = Bitmap.createBitmap(wIDth,height,Bitmap.Config.ARGB_8888);    bmp.copyPixelsFromBuffer(buf);    bmp.compress(Bitmap.CompressFormat.PNG,90,bos);    bmp.recycle();}catch(fileNotFoundException e){    e.printstacktrace();}finally{    try{        if(bos != null)            bos.close();    }    catch(IOException e){        e.printstacktrace();    }}

您还必须确保对内存具有读/写访问权限,并确保在运行时向用户询问这些权限,并且清单中包含以下内容:

<uses-permission androID:name="androID.permission.WRITE_EXTERNAL_STORAGE"/><uses-permission androID:name="androID.permission.READ_EXTERNAL_STORAGE"/>
总结

以上是内存溢出为你收集整理的android-如何在替换文件之前从内存中删除文件全部内容,希望文章能够帮你解决android-如何在替换文件之前从内存中删除文件所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1081036.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-27
下一篇 2022-05-27

发表评论

登录后才能评论

评论列表(0条)

保存