The task is to save to the file all links in the specified URL. While reading through the BufferedReader, a NullPointerException crashes when using the do while in the if (buffer.indexOf ("<a ")> 0) } line if (buffer.indexOf ("<a ")> 0) } , and when using for everything works, although in theory both cycles do the same thing. Tell me why. Previously, without problems, used both one and the other cycle.
Crashes:
public static void getLinks(String link, String file) { StringBuilder sb = new StringBuilder(); try { URL url = new URL(link); HttpURLConnection connect = (HttpURLConnection) url.openConnection(); BufferedReader input = new BufferedReader(new InputStreamReader(connect.getInputStream())); String buffer = ""; String text = ""; do { buffer = input.readLine(); if (buffer.indexOf("<a ") > 0) { // NullPointerException if (buffer.indexOf("</a") > 0) { sb.append(buffer.substring(buffer.indexOf("<a "), buffer.indexOf("</a") + 4)) .append(System.lineSeparator()); text = ""; } else { text = buffer.substring(buffer.indexOf("<a ")); } } else if (text.length() > 0) { if (buffer.indexOf("</a") > 0) { sb.append(text).append(text + buffer.substring(1, buffer.indexOf("</a") + 4)) .append(System.lineSeparator()); text = ""; } else { text += buffer; } } } while (buffer != null); } catch (IOException e) { System.out.println(e); } try (ObjectOutputStream links = new ObjectOutputStream(new FileOutputStream(file))) { links.writeObject(sb.toString()); System.out.println("File " + file + " was saved!"); } catch (IOException e) { System.out.println("Error save file!"); } } Works:
public static void getLinks(String link, String file) { StringBuilder sb = new StringBuilder(); try { URL url = new URL(link); HttpURLConnection connect = (HttpURLConnection) url.openConnection(); BufferedReader input = new BufferedReader(new InputStreamReader(connect.getInputStream())); String buffer = ""; String text = ""; for (; (buffer = input.readLine()) != null;) { // работает if (buffer.indexOf("<a ") > 0) { if (buffer.indexOf("</a") > 0) { sb.append(buffer.substring(buffer.indexOf("<a "), buffer.indexOf("</a") + 4)) .append(System.lineSeparator()); text = ""; } else { text = buffer.substring(buffer.indexOf("<a ")); } } else if (text.length() > 0) { if (buffer.indexOf("</a") > 0) { sb.append(text).append(text + buffer.substring(1, buffer.indexOf("</a") + 4)) .append(System.lineSeparator()); text = ""; } else { text += buffer; } } } } catch (IOException e) { System.out.println(e); } try (ObjectOutputStream links = new ObjectOutputStream(new FileOutputStream(file))) { links.writeObject(sb.toString()); System.out.println("File " + file + " was saved!"); } catch (IOException e) { System.out.println("Error save file!"); } }
buffer = input.readLine(), only it is built into the condition of thefor (; (buffer = input.readLine()) != null;)- Sergeydo-whilehere looks inappropriate and requires additional. checks fornullin the body of the loop. - Regent