【发布时间】:2020-11-12 02:23:03
【问题描述】:
你好,我正在尝试做这样的事情:
private Byte[] getImage() throws IOException {
String imageUrl = ServletContext.class.getClassLoader()
.getResource("static/anImage.jpg")
.getFile();
Byte[] byteObject = new Byte[imageUrl.getBytes().length];
int i = 0;
for (Byte b : imageUrl.getBytes()){
byteObject[i++] = b;
}
return byteObject;
}
但这是错误的。那么如何从特定目录中获取文件呢?谢谢。
ps。 我可以这样做:
File file = new File("image.jpg");
byte[] content = Files.readAllBytes(file.toPath());
但它仍然是仅来自主文件夹的路径。不知道如何为资源/图像文件夹编程。
【问题讨论】:
-
您可以将文件作为Resource 读取,然后从资源中获取
inputstream并转换为字节 -
好的。什么是类路径:?它的某种文件夹?资源?
-
谢谢,这太棒了。如果您将其发布,我会接受它作为答案。
-
完成!删除评论并添加答案。