Java 如何使用相对于Jersey中上下文根的路径读取文件?
我正在用球衣学习休息。我成功地创建了陈词滥调的Hello World应用程序。现在(只是为了学习目的),我试图通过字节流返回一个图像文件。但是,我得到一个文件无法读取的Java 如何使用相对于Jersey中上下文根的路径读取文件?,java,rest,jersey,Java,Rest,Jersey,我正在用球衣学习休息。我成功地创建了陈词滥调的Hello World应用程序。现在(只是为了学习目的),我试图通过字节流返回一个图像文件。但是,我得到一个文件无法读取的IOException。以下是我的资源类: @Path("/image/{file}") public class ImageResource { @Context private UriInfo uri; @GET @Produces("image/jpg") public Response ge
IOException
。以下是我的资源类:
@Path("/image/{file}")
public class ImageResource
{
@Context
private UriInfo uri;
@GET
@Produces("image/jpg")
public Response getFullImage(@PathParam("file") String fileName)
{
Response response = null;
String contextRoot = getUri().getBaseUri().toString();
try
{
BufferedImage image = ImageIO.read(new File(contextRoot + "/images/" + fileName));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", baos);
byte[] imgBytes = baos.toByteArray();
response = Response.ok(new ByteArrayInputStream(imgBytes)).build();
}
catch (IOException e)
{
System.err.println("Error reading image file..." + e.getMessage());
e.printStackTrace();
}
return response;
}
private UriInfo getUri() {
return uri;
}
}
图像存储在WebContent/images/image001.jpg
下,我使用的URL为:http://localhost:8080/REST/image/image001.jpg
点击资源
有人能告诉我异常的原因吗?由于资源嵌入到war/jar中,您需要使用类加载器为您加载它: 比如:
@Path("/image/{file}")
public class ImageResource
{
@Context
private UriInfo uri;
@GET
@Produces("image/jpg")
public Response getFullImage(@PathParam("file") String fileName)
{
Response response = null;
String contextRoot = getUri().getBaseUri().toString();
try
{
// load resource via classloader since it's embedded in war/jar
BufferedImage image = ImageIO.read(ImageResource.class.
getResourceAsStream(/images/" + fileName));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", baos);
byte[] imgBytes = baos.toByteArray();
response = Response.ok(new ByteArrayInputStream(imgBytes)).build();
}
catch (IOException e)
{
System.err.println("Error reading image file..." + e.getMessage());
e.printStackTrace();
}
return response;
}
private UriInfo getUri() {
return uri;
}
}
您应该以URL的形式访问图像。 对我来说,这很有效:
String path=uriInfo.getBaseUri().toString();
path=path.substring(0, path.lastIndexOf("/rest"))+"/img/"+foto;
try {
URL pathUrl=new URL(path);
BufferedImage image=ImageIO.read(pathUrl);
ByteArrayOutputStream baos=new ByteArrayOutputStream();
ImageIO.write(image, "jpg", baos);
byte[] imgBytes=baos.toByteArray();
return Response.ok(new ByteArrayInputStream(imgBytes)).build();
}
请确保不包括restful路径。这是问题中的一个输入错误,还是您真的点击了/REST/image/image001.jpg(单数图像-应该是图像)我不应该使用单数图像,因为我在
@path
注释中使用了相同的路径?如果我错了,请纠正我。我是新来的:)哎呀,我错过了,你所做的(URL中的“图像”和磁盘上的“图像”)从技术角度来看是可以的,但肯定会引起混淆。如果资源嵌套在您的jar/war中,您不能只创建一个指向它的文件,因为它本身不是一个文件。似乎不起作用:(我在这一行收到一个RunTimeException,消息为input==null
:BuffereImage=ImageIO.read(ImageResource.class.getResourceAsStream(/images/“+fileName));