2014-11-07 1 views
0

나는 몇 가지 코드를BufferedReader를 재설정하지 않는 방법은 무엇입니까?

public static void main(String[] args) throws HttpException, IOException, 
     JSONException { 
    // TODO Auto-generated method stub 
    try { 
     URL murl = new URL(
       "http://www.baidu.com/link?url=NaethV_J2hSPVx_OdPlHk73964mU4LcwWkJmVUV4vIkuCXRf1y09ufRZVwkHJqSAa2mMSCoTLYVhGv2AyV_04_"); 
     HttpURLConnection conn = (HttpURLConnection) murl.openConnection(); 
     conn.setRequestProperty(
       "User-Agent", 
       "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36"); 
     conn.setConnectTimeout(10000); 

     conn.connect(); 

     String strencoding = null; 


     Map<String, List<String>> map = conn.getHeaderFields(); 
     Set<String> keys = map.keySet(); 
     Iterator<String> iterator = keys.iterator(); 


     String key = null; 
     String tmp = null; 
     while (iterator.hasNext()) { 
      key = iterator.next(); 
      tmp = map.get(key).toString().toLowerCase(); 


      if (key != null && key.equals("Content-Type")) { 
       System.out.println(tmp); 
       int m = tmp.indexOf("charset="); 
       if (m != -1) { 
        strencoding = tmp.substring(m + 8).replace("]", ""); 

       } 
      } 
     } 
     strencoding = strencoding == null ? "UTF-8" : strencoding; 

     conn.getResponseCode(); 
     // conn.connect(); 
     String href = conn.getURL().toString(); 
     System.out.println(href); 
     href = href.replace("http://", ""); 
     try { 
      href = href.split("/")[0]; 
     } catch (Exception eee) { 

     } 
     /* 
     * ParseDomainName pdn = new ParseDomainName(href); 
     * System.out.println("Your host IP is: " + 
     * pdn.getMyIP().getHostAddress()); 
     * System.out.println("The Server IP is :" + 
     * pdn.getServerIP().getHostAddress()); // InputStream inputstream = 
     * conn.getInputStream(); 
     */ 

     BufferedReader reader = new BufferedReader(new InputStreamReader(
       conn.getInputStream(), strencoding)); 

     String lines; 
     int i = 1; 
     while ((lines = reader.readLine()) != null) { 

      if (lines.toLowerCase().indexOf("charset") > 0) { 
       System.out.println(lines); 
       String strtmp = lines; 
       int inttmp = strtmp.indexOf("charset"); 
       if (inttmp > -1) { 
        System.out.println(strtmp.length()); 
        strencoding = strtmp 
          .substring(inttmp + 7, strtmp.length()) 
          .replace("=", "").replace("/", "") 
          .replace("\"", "").replace("\'", "") 
          .replace(" ", "").replace("<", "") 
          .replace(">", ""); 
        break; 
       } 
      } 
      i++; 
     } 

     reader.mark(0); 
     reader.reset(); 
     reader = new BufferedReader(new InputStreamReader(
       conn.getInputStream(), strencoding)); 

     while ((lines = reader.readLine()) != null) { 
      System.out.println(i + " " + lines); 
      if (lines.toLowerCase().indexOf("icp") > 0) { 
       // System.out.println(i + " " + lines); 
      } 
      i++; 
     } 
     System.out.println(i + "---" + strencoding); 
     reader.close(); 
     conn.disconnect(); 
    } catch (Exception e2) { 
     e2.printStackTrace(); 

    } 

} 

마지막 while 루프, 첫 번째 루프에서 내가 페이지 캐릭터 세트를 확인하고 휴식, 를 작성하고 나는 독자를 재설정하고 readLine 다시 하지만 seconed 루프, 그것은 시작 첫 번째 루프 끝 위치에서 enter image description here

때로는 그런 seconed 루프에서 아무것도 읽을 수 없습니다 : enter image description here

그래서 문제가 무엇을

가끔 그런 결과를 출력한다?

+0

왜 당신이하고있는 마지막 while 루프 바로 전에 this : reader = new BufferedReader (...); –

답변

0
reader = new BufferedReader(new InputStreamReader(
     conn.getInputStream(), strencoding)); 

이 줄로 인해 코드가 새 판독기를 만드는 경우 판독기가 처음부터 시작됩니다.

+0

'strencoding'이 변경 되었기 때문에 문제가 발생합니다. – chanjianyi

1

전에 앞에 첫 번째 while 루프를 호출해야합니다. reader.mark()는 기본적으로 reader의 현재 위치를 저장하므로 reader.reset()을 호출 할 때 해당 위치로 돌아갈 수 있습니다.

reader.mark()에도 0을 전달하고 싶지는 않습니다. 아래 매개 변수에 대한 Java 스펙을 참조하십시오.

readAheadLimit - 마크를 보존하면서 읽을 수있는 문자 수 제한. 이 제한 또는 그 이상까지 문자를 읽은 후에 스트림을 재설정하려는 시도가 실패 할 수 있습니다. 한계 값이 입력 버퍼의 크기보다 크면 크기가 한계보다 작지 않은 새 버퍼가 할당됩니다. 따라서 큰 값은 신중히 사용해야합니다.

(즉, 0을 전달하면 쓸모가 없습니다.) mark()와 reset() 사이에 읽힌 문자 수보다 큰 숫자를 전달해야합니다.

+0

Yogesh_D가 지적했듯이 코드에도 다른 문제가 있습니다. – gharrma

0

마지막으로, 나는이 문제가 conn.getInputStream()에, 이미 첫 번째 루프 후 변경, 그래서 약간의 수정을 한 것입니다 발견, 입력 스트림을 복제, 지금은 괜찮 :

public static void main(String[] args) throws HttpException, IOException, 
     JSONException { 
    // TODO Auto-generated method stub 
    try { 
     URL murl = new URL(
       "http://www.baidu.com/link?url=NaethV_J2hSPVx_OdPlHk73964mU4LcwWkJmVUV4vIkuCXRf1y09ufRZVwkHJqSAa2mMSCoTLYVhGv2AyV_04_"); 
     HttpURLConnection conn = (HttpURLConnection) murl.openConnection(); 
     conn.setRequestProperty(
       "User-Agent", 
       "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36"); 
     conn.setConnectTimeout(10000); 

     conn.connect(); 

     String strencoding = null; 



     strencoding = strencoding == null ? "UTF-8" : strencoding; 

     conn.getResponseCode(); 
     // conn.connect(); 
     String href = conn.getURL().toString(); 
     System.out.println(href); 
     href = href.replace("http://", ""); 
     try { 
      href = href.split("/")[0]; 
     } catch (Exception eee) { 

     } 


     InputStream inputStream=conn.getInputStream(); 
     ByteArrayOutputStream baos = new ByteArrayOutputStream(); 


     byte[] buffer = new byte[1024]; 
     int len; 
     while ((len = inputStream.read(buffer)) > -1) { 
      baos.write(buffer, 0, len); 
     } 
     baos.flush(); 


     InputStream copyInputStream1 = new ByteArrayInputStream(baos.toByteArray()); 
     InputStream copyInputStream2 = new ByteArrayInputStream(baos.toByteArray()); 

     BufferedReader reader = new BufferedReader(new InputStreamReader(
       copyInputStream1, strencoding)); 

     String lines; 
     int i = 1; 

     while ((lines = reader.readLine()) != null) { 

      if (lines.toLowerCase().indexOf("charset") > 0) { 
       System.out.println(lines); 
       String strtmp = lines; 
       int inttmp = strtmp.indexOf("charset"); 
       if (inttmp > -1) { 
        System.out.println(strtmp.length()); 
        strencoding = strtmp 
          .substring(inttmp + 7, strtmp.length()) 
          .replace("=", "").replace("/", "") 
          .replace("\"", "").replace("\'", "") 
          .replace(" ", "").replace("<", "") 
          .replace(">", ""); 
        //break; 
       } 
      } 
      i++; 
     } 


     reader = new BufferedReader(new InputStreamReader(
       copyInputStream2, strencoding)); 

     while ((lines = reader.readLine()) != null) { 
      //System.out.println(i + " " + lines); 
      if (lines.toLowerCase().indexOf("icp") > 0) { 
       System.out.println(i + " " + lines); 
      } 
      i++; 
     } 
     System.out.println(i + "---" + strencoding); 
     reader.close(); 
     conn.disconnect(); 
    } catch (Exception e2) { 
     e2.printStackTrace(); 

    } 

}