1

我正在研究 j2me 移动应用程序部分。我必须使用 http 连接和短信格式(使用短信网关)发送消息。

当我尝试执行此操作时,java.io.IOException: Resource limit exceeded for file handles正在我的控制台中抛出。

如何避免这种情况?这是我的连接代码:

public boolean sendViaHTTP(String message)
{

    System.out.println("enter HTTP Via");
HttpConnection httpConn = null;

String url = "http://xxx.com/test.php";

System.out.println("URL="+url);
InputStream is = null;
OutputStream os = null;
try 
{
    // Open an HTTP Connection object
    httpConn = (HttpConnection)Connector.open(url);
    // Setup HTTP Request to POST
    httpConn.setRequestMethod(HttpConnection.POST);
    httpConn.setRequestProperty("User-Agent",
    "Profile/MIDP-2.0 Confirguration/CLDC-2.0");
    httpConn.setRequestProperty("Accept_Language","en-US");
    //Content-Type is must to pass parameters in POST Request
    httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    String value = System.getProperty("com.nokia.network.access");
    os = httpConn.openOutputStream();
    String params;
    params = "message=" + message;
    os.write(params.getBytes());// input writes in server side

    // Read Response from the Server
    StringBuffer sb = new StringBuffer();
    is = httpConn.openDataInputStream();
    int chr;
    while ((chr = is.read()) != -1)
    sb.append((char) chr);

    Response = sb.toString();

    //switchDisplayable("", getForm());

    //System.out.println("REsponse="+Response);
}
catch(IOException ex)
{
    System.out.println(ex);
    return false;
}
catch (Exception ex)
{
    System.out.println(ex);
    return false;
} 
finally 
{
    try 
    {
        if(is!= null)
        is.close();
        if(os != null)
        os.close();
        if(httpConn != null)
            httpConn.close();
    } 
    catch (Exception ex)
    {
        System.out.println(ex);
    }
}
return true;

}
4

1 回答 1

3

该异常(很可能)发生,因为在您的应用程序中的某个地方,您在完成对流的读取/写入后并未关闭流。

为了说明,如果这个语句

   if (is != null) is.close();

抛出异常(例如 an IOException),则finally块中的剩余语句将不会被执行。这可能会泄漏文件描述符。

问题也可能完全出在代码的另一部分,但异常消息清楚地指出了您的应用程序使用太多文件描述符的问题,最可能的原因是资源泄漏。

于 2012-07-20T05:20:53.507 回答