java - getResourceAsStream 的目录列表行为是否记录在任何地方?

标签 java

各种答案(例如 Get a list of resources from classpath directory)表明,如果您在目录上调用 getResourceAsStream,返回的流将包含目录中的项目列表,每行一个。这似乎没有记录在 ClassLoader 中Javadoc。它是在其他任何地方指定的,还是只是人们开始依赖的实现细节?

最佳答案

看起来这在任何地方都没有适当的记录。

ClassLoader.getResourceAsStream 的 Javadoc 中,您可以推断出 getResourceAsStream 与执行 getResource 然后调用 URL 是一样的.openStream 在生成的 URL 上,因为 Javadoc 指向 getResource 方法,该方法返回 URL。但它显然没有拼写到那种程度的准确性。

public InputStream getResourceAsStream(String name)

Returns an input stream for reading the specified resource. The search order is described in the documentation for getResource(String).

然后,更好地记录 URL.openStream:

public final InputStream openStream() throws IOException

Opens a connection to this URL and returns an InputStream for reading from that connection. This method is a shorthand for: openConnection().getInputStream()

然后,由于 URL.openConnection() 返回 URLConnection 的子类,假设您在类路径中使用了本地目录,您需要查看 FileURLConnection,然后在方法中getInputStream .

正如您在下面的方法中看到的,如果类路径中的 file:/// URL 指向一个目录,那么它会返回一个 InputStream,其中包含所有目录中的文件以排序的方式。 (有趣的细节,它使用平台默认编码 - 很高兴知道您何时想读回数据)

public synchronized InputStream getInputStream()
    throws IOException {

    int iconHeight;
    int iconWidth;

    connect();

    if (is == null) {
        if (isDirectory) {
            FileNameMap map = java.net.URLConnection.getFileNameMap();

            StringBuffer buf = new StringBuffer();

            if (files == null) {
                throw new FileNotFoundException(filename);
            }

            Collections.sort(files, Collator.getInstance());

            for (int i = 0 ; i < files.size() ; i++) {
                String fileName = files.get(i);
                buf.append(fileName);
                buf.append("\n");
            }
            // Put it into a (default) locale-specific byte-stream.
            is = new ByteArrayInputStream(buf.toString().getBytes());
        } else {
            throw new FileNotFoundException(filename);
        }
    }
    return is;
}

结论:

它没有正确记录,它是一个实现细节,它可能会在未来的版本中发生变化,尽管这不太可能。

关于java - getResourceAsStream 的目录列表行为是否记录在任何地方?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43954554/

相关文章:

java - 按下按钮时退出 fragment 或 Activity

java - Android Retrofit2 泛型方法

javascript - 对具有 "A/B"格式的数字的数组进行排序?

java - java的二叉树前序、后序和中序

java - 屏幕超时时调用 Activity onPause 方法吗?

java - Spring OAuth2.0 : Where does spring store the access token?

java - 在 JFileChooser 保存对话框中强制使用 ".png"

java - 为什么 2^31 不能被 n 整除?

java - Spring @Cacheable 分页方法

java - 自旋锁的替代品