0

I am trying to set up a simple test web server in Java but when I create a Path object the result is with backslashes instead of forward slashes which I think is causing it to return a 404. Is there a way to use "file.separator" with a Path object?

Check filepath & return response

Path filePath = getFilePath(path);
if (Files.exists(filePath)) {
  String contentType = guessContentType(filePath);
  sendResponse(client, "200 OK", contentType, Files.readAllBytes(filePath));
} else {
  // 404
  System.out.println("FILEPATH: " + filePath);
  byte[] notFoundContent = "<!DOCTYPE html><h2>Not Found</h2></html>".getBytes();
  sendResponse(client, "404 Not Found", "text/html", notFoundContent);
}

Filepath function

private static Path getFilePath(String path) {
  System.out.println("PATH: " + path);
  
  if ("/".equals(path)) {
    path = "/index.html";
  }
  return Paths.get("/tmp/www", path);
}

Result

PATH: /
FILEPATH: \tmp\www\index.html
...
PATH: /favicon.ico
FILEPATH: \tmp\www\favicon.ico
Kasey Chakos
  • 75
  • 1
  • 7
  • Hi, please see if you get any closer to a solution by going to https://stackoverflow.com/questions/5971964/when-should-i-use-file-separator-and-when-file-pathseparator. Hope it helps! :) – Kaj Hejer Mar 02 '21 at 21:28

1 Answers1

0

I needed to point to the current directory "." or Paths.get("."); and use File.separator inside of the getFilePath function.

private static Path getFilePath(String path) {
  String fs = File.separator;

  if ("/".equals(path)) {
    path = "." + fs + "index.html";
  }
  return Paths.get("." + fs +"tmp" + fs + "www" + fs, path.split("/"));
}
Kasey Chakos
  • 75
  • 1
  • 7