【问题标题】:Cant able to delete a file in SD card using file connection -- Blackberry无法使用文件连接删除 SD 卡中的文件 - 黑莓
【发布时间】:2011-08-26 05:43:46
【问题描述】:

我开发了一个黑莓应用程序,其中我有视频控制来捕获图像然后我将图像以我想要的名称保存在根目录中并显示屏幕...在重新捕获按钮中单击我再次捕获再次图像,我正在删除以前的图像并使用文件连接将新图像以相同的名称保存在相同的路径中。我的问题是它在模拟器中工作正常。但是当我在设备中测试时,当我尝试删除以前的图像以保存新图像时,它会抛出错误。它会抛出“net.rim.device.api.io.file.fileioexception:文件正在使用中” ..请帮帮我..


@arhimed, @juanmabaiu 这是在设备中测试时捕获并抛出异常的函数。

 public void fieldChanged( final byte[] _raw )
{
    try
    {    
        flag ++;
        // Create the connection to a file that may or
        // may not exist.
        FileConnection file = (FileConnection)Connector.open(FILE_NAME + "_front" + EXTENSION);

        // If the file exists, increment the counter until we find
        // one that hasn't been created yet.
        while( file.exists() )
        {
            file.delete();
            file = (FileConnection)Connector.open( FILE_NAME + "_front" + EXTENSION );
        }          

        //FileConnection file_temp = (FileConnection)Connector.open(FILE_NAME + "tempimg" + EXTENSION);
        //file_temp.delete();
        // We know the file doesn't exist yet, so create it
        file.create();

        // Write the image to the file
        OutputStream out = file.openOutputStream();
        out.write(_raw);

        // Close the connections
        out.close();
        file.close();
        //Dialog.inform( "Saved to " + FILE_NAME + "_front" + EXTENSION );
    }
    catch(Exception e)
    {
        home.errorDialog("ERROR " + e.getClass() + ":  " + e.getMessage());
        Dialog.inform( "File not saved this time");
    }        
}

【问题讨论】:

  • 确保您在保存或删除文件后关闭了所有流。
  • 试试 Arhimed 在上述评论中所说的话。如果它不能修复它,请添加一些代码。
  • hi arhimed 和 juanmabaiu.. 代码中的一切都很好.. 它在模拟器中完美运行。仅在设备中测试时显示错误..

标签: blackberry


【解决方案1】:

我也遇到了这个问题,但是当我尝试将图像保存在设备内存而不是 SD 卡上时。以下代码可以删除图片:

if (file.exists()) {
    file.delete();
    file.close();
}

【讨论】:

    【解决方案2】:

    这段代码很臭:

    while( file.exists() )
    {
        file.delete();
        file = (FileConnection)Connector.open( FILE_NAME + "_front" + EXTENSION );
    }
    

    事实上,如果文件存在,那么你删除它,但你忘记了刚刚删除文件的FileConnection 实例。我想这可能是原因。您需要立即关闭FileConnection 实例。以下是BB API 对此的评价:

    同样,文件或目录也可以使用 FileConnection.delete() 方法删除,开发者在删除后应立即关闭连接,以防止异常访问到不存在的文件或目录的连接。

    所以尝试使用以下内容:

    if (file.exists()) {
        file.delete();
        file.close();
        file = (FileConnection) Connector.open(FILE_NAME + "_front" + EXTENSION);
    }
    

    要强调的另一点是代码非常自信/乐观,它不能正确处理极端情况。例如。如果out.write(_raw); 因任何原因失败(例如,没有可用空间)怎么办? FileConnection 和 OutputStream 会被关闭吗?不,因此您需要添加一个finally 块,以确保您实际上没有打开任何东西。

    【讨论】:

    • 感谢您的回复。你说的我已经试过了。但我仍然面临同样的问题。
    • 某些东西肯定会保存该文件的系统资源。试着弄清楚它到底是做什么的。
    • 上述 if 循环在模拟器中也能完美运行,并在设备中引发异常。如果你愿意,我可以将我的整个代码邮寄给你。你能帮我解决这个问题吗?
    • 对不起,我无法处理您的电子邮件请求。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多