Java Reference
In-Depth Information
duces annotation so that the JAX-RS implementation knows how to set the Content-Type
header.
java.io.File
Instances of java.io.File can also be used for input and output of any media type. Here's
an example for returning a reference to a file on disk:
@Path ( "/file" )
public
public class
class FileService
FileService {
private
private static
static final
final String basePath = "..." ;
@GET
@Path ( "{filepath: .*}" )
@Produces ( "text/plain" )
public
public File getFile ( @PathParam ( "filepath" ) String path ) {
return
return new
new File ( basePath + path );
}
In this example, we're using an injected @PathParam to create a reference to a real file that
exists on our disk. We create a java.io.File based on this path and return it as our re-
sponse body. The JAX-RS implementation will open up an InputStream based on this file
reference and stream into a buffer that is written back incrementally to the response's output
stream. We must specify the @Produces annotation so that the JAX-RS implementation
knows how to set the Content-Type header.
You can also inject java.io.File instances that represent the incoming request response
body. For example:
@POST
@Path ( "/morestuff" )
public
public void
void post ( File file ) {
Reader reader = new
new FileInputStream ( file ));
LineNumberReader lineReader = new
new Reader ( new
new LineNumberReader ( reader );
ddo {
String line = lineReader . readLine ();
iif ( line != null
null ) System . out . println ( line );
} while
while ( line != null
null );
}
The way this works is that the JAX-RS implementation creates a temporary file for input on
disk. It reads from the network buffer and saves the bytes read into this temporary file. In our
example, we create a java.io.FileInputStream from the java.io.File object that was
Search WWH ::




Custom Search