Reputation: 87
Hello im trying to do something like this:
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;
}
But it's wrong. So how to pick up a file from specific directory? Thanks.
ps. I can do something like this:
File file = new File("image.jpg");
byte[] content = Files.readAllBytes(file.toPath());
But still its a path only from the main folder. Dont know how to program for the resources/images folder.
Upvotes: 0
Views: 502
Reputation: 313
In Spring you can use Resources to achieve your goal:
Resource resource = new ClassPathResource("static/anImage.jpg");
byte[] bytes = resource.getInputStream().readAllBytes();
Upvotes: 1
Reputation: 21
Don't reinvent the wheel and use e.g. Apache Commons for convert a File to byte array. Read more FileUtils.readFileToByteArray(File input)
The way you loading resources seems to be the proper one.
Ensure that the loaded file is in proper location (src/main/resources).
Do you have any particular error or stack trace which describes the issue.
Upvotes: 1