2012-01-16 13 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(); 
     } 
    } 
}