title: Java check com port connection
body: <p>I am looking for a bit of efficient code that can assist me in monitoring if a com port is still open using the <code>RX/TX</code> libraries.</p>
  
  <p>Lets say I have a hardware device that communicates to the PC using a virtual com port and that device can be plugged in and out at any time. I want to show a connection status on the pc.</p>
  
  <p>I have tried this with something like a buffered reader below and it registered that the device gets disconnected but I have to re-open the port from scratch in another method. </p>
  
  <p>I am looking from something short like <code>comPort.isOpen ()</code> or something?</p>
  
  <pre><code>// Set the value of is running
  Start.isRunning = true;
  
  // Check to see if the device is connected
  while (Start.isRunning) {
      // Try to connect to the device
      try {
          // Create a Buffered Reader
          BufferedReader reader = new BufferedReader(
                  new InputStreamReader(serialPort.getInputStream()));
  
          // Read the output
          if (Character.toString((char) reader.read()).equalsIgnoreCase(
              "^")) {
              // Set the connected flag
              Start.CONNECTED_FLAG = true;
  
              // Set the connected fag
              AddComponents.TFconnected.setText("Connected");
          }
  
          // Close the reader
          reader.close();
  
          // Let the thread sleep
          Thread.sleep(500);
      }
  
      // Catch a error if the device is disconnected
      catch (Exception err) {
          // Set the connected flag
          Start.CONNECTED_FLAG = false;
          // Set the connected fag
          AddComponents.TFconnected.setText("Disconnected");
  
          // Let the thread sleep
          Thread.sleep(500);
      }
  }
  </code></pre>