关于java.io.IOException问题

  这个是一个很莫名的问题,通常让人很难发现。java.io.IOException: stream closed   意思是说流关闭. 天啊,我没有关闭它啊。小弟就遇到过这个问题:

public class LocationService {

    /**
     * 借助Google MAP 通过用户当前经纬度 获得用户当前城市
     */
    static final String GOOGLE_MAPS_API_KEY = "0835yI5X5qhWP3POFjEeQhZwN1xgAt9rmv5688w";

    private Context mContext;
    private LocationManager locationManager;
    
    private String city = "not found";
    private String address = "not found";

    public LocationService(Context context) {
        mContext = context;
        
        
    }

    public String getCity() {
        return city;
    }
    
    public String getAddress(){
        return address;
    }
    /**
     * get the current-local Location
     * @return
     */
    private Location getLocation(){
        Location currentLocation;
        this.locationManager = (LocationManager)mContext.getSystemService(Context.LOCATION_SERVICE);
        currentLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if(currentLocation == null)
            currentLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        return currentLocation;
    }
    
    /**
     * parse the location, the you could call getCity() or getAddress()
     * @param location
     */
    public void reverseGeocode(Location location) {
        // http://maps.google.com/maps/geo?q=40.714224,-73.961452&output=json&oe=utf8&sensor=true_or_false&key=your_api_key
        HttpURLConnection connection = null;
        URL serverAddress = null;
        if(location==null)
            location = getLocation();
        try {
            // build the URL using the latitude & longitude you want to lookup
            // NOTE: I chose XML return format here but you can choose something
            serverAddress = new URL("http://maps.google.com/maps/geo?q="
                    + Double.toString(location.getLatitude()) + ","
                    + Double.toString(location.getLongitude())
                    + "&output=xml&oe=utf8&sensor=true&key="
                    + GOOGLE_MAPS_API_KEY);
            connection = null;
            // Set up the initial connection
            connection = (HttpURLConnection) serverAddress.openConnection();
            connection.setRequestMethod("GET");
            connection.setDoOutput(true);
            connection.setReadTimeout(10000);
            connection.connect();

            try {
                //InputStreamReader isr = new InputStreamReader(connection.getInputStream());
                String result = read(connection.getInputStream());
                System.out.println("result: " + result);

                SAXParserFactory factory=SAXParserFactory.newInstance();
                InputSource is = new InputSource(connection.getInputStream());
                XMLReader reader;
                SAXHandler saxHandler = new SAXHandler();
                try {
                    reader = factory.newSAXParser().getXMLReader();
                    reader.setContentHandler(saxHandler); 
                    is.setEncoding("utf-8");
                    reader.parse(is); 
                } catch (Exception e) {
                    e.printStackTrace();
                } 
                
                city = saxHandler.getCity();
                address = saxHandler.getAddress();
                System.out.println("address: "+saxHandler.getAddress());
                System.out.println("city: "+saxHandler.getCity());
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println("GetCity.reverseGeocode()" + ex);
        }

    }
    
    private  String read(InputStream in) throws IOException {
        StringBuilder sb = new StringBuilder();
        BufferedReader r = new BufferedReader(new InputStreamReader(in), 1024);
        for (String line = r.readLine(); line != null; line = r.readLine()) {
            sb.append(line);
        }
        in.close();
        return sb.toString();
    }
}

  一下运行就会出现这个错误:java.io.IOException : stream closed  .   搞了好久才发现我httpurlconnction.getInputStream()我上面调用了两次。。。。  真是想不到对于HttpUrlConnection调用两次getInputSream()竟会关闭流。。。。  正确做法保留一个即可

原文地址:https://www.cnblogs.com/slider/p/2588266.html