【问题标题】:closing InputStream with AsyncTask用 AsyncTask 关闭 InputStream
【发布时间】:2016-12-09 00:51:20
【问题描述】:

我有以下代码。它运作良好,但我意识到我从未关闭过InputStream。研究,似乎我应该通过在我的一个捕获后添加 finally 来关闭它。

Q1:我需要关闭InputStream吗?

Q2:如果是,怎么做?

这是我的代码示例:

    public void refreshWind (final double lat, final double lon){

    new AsyncTask<String, Void, String>() {
        @Override
        protected String doInBackground(String... strings) {

            String YQL = String.format("select * from weather.forecast where woeid in (SELECT woeid FROM geo.places WHERE text=\"(%s,%s)\")", lat, lon);
            String endpoint = String.format("https://query.yahooapis.com/v1/public/yql?q=%s&format=json", Uri.encode(YQL));

            try {
                URL url = new URL(endpoint);
                URLConnection connection =url.openConnection();
                connection.setReadTimeout(10 *1000);         
                connection.setConnectTimeout(10 *1000);      
                InputStream inputStream =connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder result = new StringBuilder();
                String line;
                while ((line = reader.readLine()) !=null){
                    result.append(line);
                }
                return result.toString();
            }catch (Exception e) {
                error = e;
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {

            if (s ==null && error !=null){
                callback.serviceFailure(error);
                return;
            }
            try {
                JSONObject data = new JSONObject(s);
                JSONObject queryResults =data.optJSONObject("query");
                int count =queryResults.optInt("count");
                if (count ==0){
                    callback.serviceFailure(new LocationWeatherException("Wind information not available at this time."));
                    return;
                }

                Channel channel = new Channel();
                channel.populate(queryResults.optJSONObject("results").optJSONObject("channel"));
                callback.serviceSuccess(channel);
            }catch (JSONException e) {
                callback.serviceFailure(e);
            }
        }
    }.execute();

}

【问题讨论】:

    标签: android android-asynctask inputstream


    【解决方案1】:

    我认为您应该在包裹您的InputStreamBufferedReader 上调用close()。如果发生异常,您应该在finally close 中调用它:

    protected String doInBackground(String... strings) {
    
        String YQL = String.format("select * from weather.forecast where woeid in (SELECT woeid FROM geo.places WHERE text=\"(%s,%s)\")", lat, lon);
        String endpoint = String.format("https://query.yahooapis.com/v1/public/yql?q=%s&format=json", Uri.encode(YQL));
        BufferedReader reader = null;
    
        try {
            URL url = new URL(endpoint);
            URLConnection connection =url.openConnection();
            connection.setReadTimeout(10 *1000);         
            connection.setConnectTimeout(10 *1000);      
            InputStream inputStream =connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder result = new StringBuilder();
            String line;
            while ((line = reader.readLine()) !=null){
                result.append(line);
            }
            return result.toString();
        } catch (Exception e) {
            error = e;
        } finally {
            // should have no effect if stream already closed
            if (reader != null) {
                reader.close();
            }
        }
        return null;
    }
    

    来自Javadoc for BufferedReader#close()

    关闭流并释放与其关联的所有系统资源。关闭流后,进一步的 read()、ready()、mark()、reset() 或 skip() 调用将引发 IOException。 关闭之前关闭的流无效。

    【讨论】:

    • 请注意close() 本身可以抛出IOException。在大多数情况下,你会默默地忽略那个。
    • @szym Point 指出,关闭流时的失败可能很有趣,例如至少用于记录。
    • 我最终得到了这个。最后 { if (reader != null) { try{ reader.close(); } 捕捉(IOException e{ }
    猜你喜欢
    • 1970-01-01
    • 2016-04-05
    • 2018-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-23
    • 2017-02-25
    • 2015-05-12
    相关资源
    最近更新 更多