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