2012-01-16 3 views
0

yahoo finance에서 .csv 파일을 다운로드하여 로컬에 저장하는이 메서드가 있습니다. 루프 중에 액세스되므로 목록에서 많은 파일을 다운로드하고 있습니다. 그러나 기호가 잘못 입력되거나 더 이상 존재하지 않거나 연결 시간이 초과되는 경우가 있습니다. 연결 시간 제한이 다시 시도되고 잘못된 기호 (URL이 작동하지 않음을 의미)가 프로그램을 끝내지 않고 건너 뛸 수 있도록이 메서드를 수정하는 방법은 무엇입니까?URLConnection에 대한 오류 처리

public static void get_file(String symbol){ 

    OutputStream outStream = null; 
    URLConnection uCon = null; 
    InputStream is = null; 

    String finance_url = "http://ichart.finance.yahoo.com/table.csv?s="+symbol; 
    String destination = "C:/"+symbol+"_table.csv"; 

    try { 
     URL Url; 
     byte[] buf; 
     int ByteRead,ByteWritten=0; 
     Url= new URL(finance_url); 

     outStream = new BufferedOutputStream(new FileOutputStream(destination)); 

     uCon = Url.openConnection(); 
     is = uCon.getInputStream();   
     buf = new byte[size]; 

     while ((ByteRead = is.read(buf)) != -1) { 
      outStream.write(buf, 0, ByteRead); 
      ByteWritten += ByteRead; 
     } 

    }catch (Exception e) { 
     System.out.println("Error while downloading "+symbol); 
     e.printStackTrace(); 
    }finally { 
     try { 
      is.close(); 
      outStream.close(); 
     }catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 
+0

귀하의 예외는 try/catch 블록에서 발견됩니다. 문제가 무엇입니까? 그러한 문제가 발생했을 때 프로그램하는 것은 무엇이며 원하는 것은 무엇입니까? –

답변

1

예외가 발생하면 다시 메서드를 호출하지 않는 이유는 무엇입니까? 예외 유형을 제한하여 재시도를 시작해야하는시기를 나타낼 수 있습니다.

public static void get_file(String symbol){ 

    OutputStream outStream = null; 
    URLConnection uCon = null; 
    InputStream is = null; 

    String finance_url = "http://ichart.finance.yahoo.com/table.csv?s="+symbol; 
    String destination = "C:/"+symbol+"_table.csv"; 

    try { 
     URL Url; 
     byte[] buf; 
     int ByteRead,ByteWritten=0; 
     Url= new URL(finance_url); 

     outStream = new BufferedOutputStream(new FileOutputStream(destination)); 

     uCon = Url.openConnection(); 
     is = uCon.getInputStream();   
     buf = new byte[size]; 

     while ((ByteRead = is.read(buf)) != -1) { 
      outStream.write(buf, 0, ByteRead); 
      ByteWritten += ByteRead; 
     } 

    }catch (Exception e) { 
     getFile(symbol); 
    }finally { 
     try { 
      is.close(); 
      outStream.close(); 
     }catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
}