[英]how to use java.nio.file.Path with file separator?
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 " 帶有路徑 object?
檢查文件路徑並返回響應
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);
}
文件路徑 function
private static Path getFilePath(String path) {
System.out.println("PATH: " + path);
if ("/".equals(path)) {
path = "/index.html";
}
return Paths.get("/tmp/www", path);
}
結果
PATH: /
FILEPATH: \tmp\www\index.html
...
PATH: /favicon.ico
FILEPATH: \tmp\www\favicon.ico
我需要指向當前目錄“。” 或Paths.get(".");
並在 getFilePath function 中使用 File.separator。
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("/"));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.