title: Closing BufferedReader and BufferedWriter when killing Java process
body: <p>I have a java program that reads logging information whilst it's being updated and writes the filtered data to a new file. When I execute this as a jar it will run until I kill the process.</p>
  
  <p>How can I make sure that when I kill this process that I close BufferedReader and BufferedWriter to prevent memory leaks? </p>
  
  <p>I have tried using try...finally block methods as suggested by others but this closes the stream whilst the program is still running. Thanks in advance.</p>
  
  <p>FileWatcher.java</p>
  
  <pre><code>import org.apache.commons.io.FileUtils;
  import org.apache.commons.lang3.StringUtils;
  
  import java.io.*
  
  public class FileWatcher implements Runnable
  {
    boolean running = true;
    File file;
    BufferedReader reader;
    BufferedWriter writer;
    String pathToLog, pathToOutput;
  
    public FileWatcher(String pathToLog, String pathToOutput)
    {
      this.pathToLog = pathToLog;
      this.pathToOutput = pathToOutput;
    }
  
    public void run()
    {
      try
      {
        file = new File(pathToOutput);
        reader = new BufferedReader(new FileReader(pathToLog));
        writer = new BufferedWriter(new FileWriter(pathToOutput));
  
        if (!file.exists())
        {
          file.createNewFile();
        }
      }
      catch (FileNotFoundException e)
      {
        e.printStackTrace();
      }
      catch (IOException e)
      {
        e.printStackTrace();
      }
  
      String line = null;
  
      System.out.println("Running...");
      while (running)
      {
        try
        {
          /* For each packet logged */
          for (int i = 0; i &lt; 7; i++)
          {
            line = reader.readLine(); //Analyse text in line
  
            /* If no text then break */
            if (line == null)
            {
              break;
            }
  
            /* If the line begins with valid IP address then break to find Src and Dest IP */
            if (line.startsWith("192", 22))
            {
              break;
            }
          }
  
          /* If line is not null then filter out the Source IP and Destination IP */
          if (line != null)
          {
            int lastIndexOfSrcIP = StringUtils.ordinalIndexOf(line, ":", 3); // Position to stop reading Source IP
            int firstIndexOfDestIP = StringUtils.ordinalIndexOf(line, "&gt;", 1) + 2; // Position to start reading Destination IP
            int lastIndexOfDestIP = StringUtils.ordinalIndexOf(line, ":", 4); // Position to stop reading Destination IP
  
            String sourceIP = line.substring(22, lastIndexOfSrcIP); // Source IP
            String destinationIP = line.substring(firstIndexOfDestIP, lastIndexOfDestIP); // Destination IP
  
            /* Check if Source IP is the IP address of the node  we are running Snort on
             * if so then don't append to malicious clients file */
            if (!(sourceIP.equals("192.168.7.5")))
            {
              //If Source IP is not in file then add it
              if (!(FileUtils.readFileToString(file).contains(sourceIP)))
              {
                writer.write(sourceIP + "\n");
                writer.flush();
              }
  
              System.out.println(sourceIP + "\t" + destinationIP);
            }
          }
          else
          {
            //Sleep whilst there are no new logging alert information
            try
            {
              Thread.sleep(1000);
            }
            catch (InterruptedException e)
            {
              running = false;
              writer.close();
              reader.close();
            }
          }
        }
        catch (IOException e)
        {
          e.printStackTrace();
        }
      }
    }
  }
  </code></pre>
  
  <p>Main.java</p>
  
  <pre><code>public class Daemon
  {
    public static void main(String[] args)
    {
      String pathToLog = args[0];
      String pathToOutput = args[1];
  
      Thread daemon = new Thread(new FileWatcher(pathToLog, pathToOutput));
      daemon.start();
    }
  }
  </code></pre>