I am doing this:
File file = new File(String.valueOf(getClass().getClassLoader().getResource("images/logo.png")));
in order to have the entire path file name.
But this instruction below fails:
byte[] fileContent = FileUtils.readFileToByteArray(file);
I am getting this exception:
java.io.FileNotFoundException: File 'file:\C:\Users\thomas\dev\workspace\myapp\target\classes\images\logo.png' does not exist
It's because it needs to have double backslash instead of single backslash (OS: Windows). Is there a way to get rid of this?
You are very close. You probably want the getResourceAsStream
function. As noted in the comments, you do NOT want to use File
for this, as it will reference things on the file system (things that will not be there once you build & deploy your app).
A simple demo of reading a Java resource is below:
public void readResourceBytes()
{
final String resourceName = "images/logo.png";
final ByteArrayOutputStream mem = new ByteArrayOutputStream();
try (final InputStream is = getClass().getClassLoader().getResourceAsStream(resourceName))
{
copy(is, mem);
}
byte[] fileContent = mem.toByteArray();
System.out.println(mem.toByteArray());
// Or, maybe you just want the ASCII text
// String fileContent = mem.toString();
// System.out.println(mem.toString());
}
// OK for binary files, not OK for text, should use Reader/Writer instead
public static void copy(final InputStream from, final OutputStream to) throws IOException
{
final int bufferSize = 4096;
final byte[] buf = new byte[bufferSize];
int len;
while (0 < (len = from.read(buf)))
{
to.write(buf, 0, len);
}
to.flush();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.