【问题标题】:Can I access resource with File object?我可以使用 File 对象访问资源吗?
【发布时间】:2013-12-31 21:56:57
【问题描述】:

我正在使用以下代码访问字体资源

      try {
            URL url = getClass().getResource("");
            log.debug("url = '{}'", url.toString());

            URI uri = url.toURI();
            log.debug("uri = '{}'", uri.toString());

            File dir = new File(uri);

            files = dir.listFiles(new FilenameFilter() {
                @Override
                public boolean accept(File dir, String name) {
                    return name.toLowerCase().endsWith(".ttf");
                }
            });

            indice = new Integer[files.length];
            delegate = new Descr[files.length];
            fileNames = new String[files.length];
            fontNames = new String[files.length];

            for(int i=0; i<files.length; ++i) {
                delegate[i] = new Descr(Font.createFont(Font.TRUETYPE_FONT, files[i]).deriveFont(FontSize));
                fileNames[i] = files[i].getName();
                fontNames[i] = delegate[i].getFont().getFontName();
            }



        } catch (URISyntaxException e) {
            throw new AssertionError(e);
        } catch (FontFormatException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

在放入 JAR 之前它一直在工作。在JAR 中会导致错误

 IllegalargumentException: URI is not hierarchicalhierarchical

那么,如何枚举JAR内部的资源呢?可以使用File吗?

【问题讨论】:

    标签: java file fonts jar embedded-resource


    【解决方案1】:

    我可以使用 File 对象访问资源吗?

    不,它们不再是文件了。

    如何枚举 JAR 中的资源?是否可以使用文件?

    每当有人问这个问题时,我都想知道为什么他们需要这样做。构建 Jar 时,创建资源列表并放入 Jar 中的“已知位置”。在运行时,获取列表,解析它,然后从那里开始。

    【讨论】:

    • 当然,如果无法生成列表,我将对其进行硬编码。就我而言,这些是字体,很容易添加新字体。
    • 发表这样的评论有什么意义吗?如果是这样,我就迷失了。
    猜你喜欢
    • 2012-03-11
    • 1970-01-01
    • 2015-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多