thomas
thomas

Reputation: 1271

Get path of file with double backslash

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?

Upvotes: 0

Views: 121

Answers (1)

JonathanDavidArndt
JonathanDavidArndt

Reputation: 2732

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();
    }

Upvotes: 1

Related Questions