title: The fastest ways to check if a file exists in java
body: <p>Currently i am tasked with making a tool that can check whether a link is correct or not using java. The link is fed from Jericho HTML Parser, and my job is only to check whether the file is exist / the link is correct or not. That part is done, the hard part is to optimize it, since my code run (i have to say) rather sluggishly on 65ms per run</p>
  
  <pre><code>public static String checkRelativeURL(String originalFileLoc, String relativeLoc){
          StringBuilder sb = new StringBuilder();
          String absolute = Common.relativeToAbsolute(originalFileLoc, relativeLoc); //built in function to replace the link from relative link to absolute path
          sb.append(absolute);
          sb.append("\t");
          try {
              Path path = Paths.get(absolute);
              sb.append(Files.exists(path));
          }catch (InvalidPathException | NullPointerException ex) {
              sb.append(false);
          }
          sb.append("\t");
          return sb.toString();
      }
  </code></pre>
  
  <p>and on this line it took 65 ms</p>
  
  <pre><code>Path path = Paths.get(absolute);
  sb.append(Files.exists(path));
  </code></pre>
  
  <p>I have tried using </p>
  
  <pre><code>File file = new File(absolute);
  sb.append(file.isFile());
  </code></pre>
  
  <p>It's still ran around 65~100ms. </p>
  
  <p>So is there any other  faster way to check whether a file exists or not other than this?</p>
  
  <p>Since i am processing more than 70k html files and every milliseconds counts, thanks :(</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>I tried listing all the files into some List, and it doesn't really helps since it take more than 20mins just to list all the file....</p>
  
  <p>The code that i use to list all the file </p>
  
  <pre><code>static public void listFiles2(String filepath){
          Path path = Paths.get(filepath);
          File file = null;
          String pathString = new String();
          try {
              if(path.toFile().isDirectory()){
                  DirectoryStream&lt;Path&gt; stream = Files.newDirectoryStream(path);
                  for(Path entry : stream){
                      file = entry.toFile();
                      pathString = entry.toString();
                      if(file.isDirectory()){
                          listFiles2(pathString);
                      }
                      if (file.isFile()){
                          filesInProject.add(pathString);
                          System.out.println(pathString);
                      }
                  }
                  stream.close();
              }
          } catch (IOException e) {
              e.printStackTrace();
          }
      }
  </code></pre>