简体   繁体   English

获取带有双反斜杠的文件路径

[英]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).这是因为它需要双反斜杠而不是单反斜杠(操作系统: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).您可能需要getResourceAsStream function。如评论中所述,您不想为此使用File ,因为它会引用文件系统上的内容(构建和部署应用程序后不会存在的内容)。

A simple demo of reading a Java resource is below:下面是一个读取 Java 资源的简单演示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM