Java Reference
In-Depth Information
byte
byte
[]
buffer
=
new
new
byte
byte
[
1000
];
int
int
wasRead
=
0
;
ddo
{
wasRead
=
stream
.
read
(
buffer
);
iif
(
wasRead
>
0
) {
baos
.
write
(
buffer
,
0
,
wasRead
);
}
}
while
while
(
wasRead
>
−
1
);
return
return
baos
.
toByteArray
();
}
Here, we're reading the full raw bytes of the
java.io.InputStream
available and using
them to create a
String
that we output to the screen:
@PUT
@Path
(
"/morestuff"
)
public
public
void
void
putMore
(
Reader reader
) {
LineNumberReader lineReader
=
new
new
LineNumberReader
(
reader
);
ddo
{
String line
=
lineReader
.
readLine
();
iif
(
line
!=
null
null
)
System
.
out
.
println
(
line
);
}
while
while
(
line
!=
null
null
);
}
For this example, we're creating a
java.io.LineNumberReader
that wraps our injected
Reader
object and prints out every line in the request body.
You are not limited to using
InputStream
and
Reader
for reading input request message
bodies. You can also return these as response objects. For example:
@Path
(
"/file"
)
public
public class
class
FileService
FileService
{
private
private static
static final
final
String basePath
=
"..."
;
@GET
@Path
(
"{filepath: .*}"
)
@Produces
(
"text/plain"
)
public
public
InputStream
getFile
(
@PathParam
(
"filepath"
)
String path
) {
FileInputStream is
=
new
new
FileInputStream
(
basePath
+
path
);
return
return
is
;
}
Here, we're using an injected
@PathParam
to create a reference to a real file that exists on
our disk. We create a
java.io.FileInputStream
based on this path and return it as our re-
sponse body. The JAX-RS implementation will read from this input stream into a buffer and
write it back out incrementally to the response output stream. We must specify the
@Pro-