簡體   English   中英

獲取帶有雙反斜杠的文件路徑

[英]Get path of file with double backslash

我這樣做:

File file = new File(String.valueOf(getClass().getClassLoader().getResource("images/logo.png")));

為了有完整的路徑文件名。
但是下面的這條指令失敗了:

byte[] fileContent = FileUtils.readFileToByteArray(file);

我收到此異常:

java.io.FileNotFoundException: File 'file:\C:\Users\thomas\dev\workspace\myapp\target\classes\images\logo.png' does not exist

這是因為它需要雙反斜杠而不是單反斜杠(操作系統:Windows)。 有沒有辦法擺脫這個?

你很親密。 您可能需要getResourceAsStream function。如評論中所述,您不想為此使用File ,因為它會引用文件系統上的內容(構建和部署應用程序后不會存在的內容)。

下面是一個讀取 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