title: How to open a file without saving it to disk
body: <p><strong>My Question:</strong> How do I open a file (in the system default [external] program for the file) without saving the file to disk?</p>
  
  <p><strong>My Situation:</strong> I have files in my resources and I want to display those without saving them to disk first. For example, I have an <code>xml</code> file and I want to open it on the user's machine in the default program for reading <code>xml</code> file without saving it to the disk first.</p>
  
  <p><strong>What I have been doing:</strong> So far I have just saved the file to a temporary location, but I have no way of knowing when they no longer need the file so I don't know when/if to delete it. Here's my <a href="http://www.sscce.org" rel="nofollow">SSCCE</a> code for that (well, it's mostly sscce, except for the resource... You'll have to create that on your own):</p>
  
  <pre><code>package main;
  
  import java.io.*;
  
  public class SOQuestion {
  
    public static void main(String[] args) throws IOException {
      new SOQuestion().showTemplate();
    }
  
    /** Opens the temporary file */
    private void showTemplate() throws IOException {
      String tempDir = System.getProperty("java.io.tmpdir") + "\\BONotifier\\";
      File parentFile = new File(tempDir);
      if (!parentFile.exists()) {
        parentFile.mkdirs();
      }
      File outputFile = new File(parentFile, "template.xml");
      InputStream inputStream = getClass().getResourceAsStream("/resources/template.xml");
      int size = 4096;
      try (OutputStream out = new FileOutputStream(outputFile)) {
        byte[] buffer = new byte[size];
        int length;
        while ((length = inputStream.read(buffer)) &gt; 0) {
          out.write(buffer, 0, length);
        }
        inputStream.close();
      }
      java.awt.Desktop.getDesktop().open(outputFile);
    }
  }
  </code></pre>