Class SimpleStaticFileServer

java.lang.Object
net.jrodolfo.java_evolution.java18.simple_web_server.SimpleStaticFileServer
All Implemented Interfaces:
AutoCloseable

public final class SimpleStaticFileServer extends Object implements AutoCloseable
Demonstrates the Java 18 Simple Web Server API.

Java 18 introduced the jwebserver command for quickly serving static files from a directory. The same JEP also introduced SimpleFileServer, which lets Java code create the same kind of local static-file server. This class wraps that API in a tiny lifecycle-friendly example for tests and study.

  • Method Details

    • start

      public static SimpleStaticFileServer start(Path rootDirectory) throws IOException
      Starts a local static-file server on an ephemeral loopback port.

      Port 0 asks the operating system to choose a free port, which keeps tests deterministic and avoids hard-coded local port conflicts.

      Parameters:
      rootDirectory - the directory to serve
      Returns:
      a started server
      Throws:
      IOException - when the server cannot be created
    • rootDirectory

      public Path rootDirectory()
      Returns the directory being served.
      Returns:
      the normalized root directory
    • port

      public int port()
      Returns the selected local port.
      Returns:
      the port chosen for this server
    • uri

      public URI uri(String path)
      Builds a URI for a file path on the local server.
      Parameters:
      path - the request path, with or without a leading slash
      Returns:
      URI pointing at this local server
    • get

      Requests a static file from the server.
      Parameters:
      path - the request path, with or without a leading slash
      Returns:
      status code and body returned by the server
      Throws:
      IOException - when the HTTP request fails
      InterruptedException - when the request is interrupted
    • close

      public void close()
      Stops the server immediately.
      Specified by:
      close in interface AutoCloseable