Anophoo

webWorker class

May 16th, 2017
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. import java.io.*;
  2. import java.net.*;
  3. import java.text.SimpleDateFormat;
  4. import java.util.Date;
  5. import javax.swing.*;
  6.  
  7. public class WebWorker extends Thread {
  8. private String urlString;
  9. private String info;
  10. private WebFrame frame;
  11. private int row;
  12.  
  13.  
  14. // updates url information
  15. public WebWorker(String url, int row, WebFrame frame) {
  16. this.urlString = url;
  17. this.info = "";
  18. this.frame = frame;
  19. this.row = row;
  20. }
  21.  
  22. @Override
  23. public void run() {
  24. download();
  25. frame.updateGUI(row, info);
  26. }
  27.  
  28. private void download() {
  29. // This is the core web/download i/o code...
  30. InputStream input = null;
  31. StringBuilder contents = null;
  32. try {
  33. URL url = new URL(urlString);
  34. long startTime = System.currentTimeMillis();
  35. URLConnection connection = url.openConnection();
  36.  
  37. // Set connect() to throw an IOException
  38. // if connection does not succeed in this many msecs.
  39. connection.setConnectTimeout(5000);
  40.  
  41. connection.connect();
  42. input = connection.getInputStream();
  43.  
  44. BufferedReader reader = new BufferedReader(new InputStreamReader(input));
  45.  
  46. char[] array = new char[1000];
  47. int len;
  48. contents = new StringBuilder(1000);
  49. while ((len = reader.read(array, 0, array.length)) > 0) {
  50. contents.append(array, 0, len);
  51. Thread.sleep(100);
  52. }
  53.  
  54.  
  55. // Successful download if we get here
  56. long endTime = System.currentTimeMillis();
  57. info = new SimpleDateFormat("HH:mm:ss").format(new Date(startTime))
  58. + " " + (endTime - startTime)
  59. + "ms " + array.length + "bytes";
  60. }
  61. // Otherwise control jumps to a catch...
  62. catch (MalformedURLException ignored) {
  63. } catch (InterruptedException exception) {
  64. // YOUR CODE HERE
  65. // deal with interruption
  66. } catch (IOException ignored) {
  67. }
  68. // "finally" clause, to close the input stream
  69. // in any case
  70. finally {
  71. try {
  72. if (input != null)
  73. input.close();
  74. } catch (IOException ignored) {
  75. }
  76. }
  77. }
  78.  
  79. }
Advertisement
Add Comment
Please, Sign In to add comment