简体   繁体   中英

Exception in thread “main” java.lang.IllegalArgumentException: URI is not hierar chical

I have seen similar questions but not sure how to fix it. I have tried changing it to input stream

public List<String> mergeInputData(List<String> s){

    List<String> mergedInputData = new ArrayList<String>();
    for (String string : s) {
        Enumeration<URL> en = getClass().getClassLoader().getResources(
                string);
        if (en.hasMoreElements()) {
            URL metaInf = en.nextElement();
            try (BufferedReader br = new BufferedReader(new FileReader(
                    new File(metaInf.toURI())))) {
                String line = "";
                while ((line = br.readLine()) != null) {
                    if (line.length() > 0)
                        mergedInputData.add(line.trim());
                }
            } catch (URISyntaxException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }

    return mergedInputData;
}

Above, string just contains the name of the file (say egample.txt)For eg am trying to read egample.txt.

It runs from eclipse though. Please suggest how can i fix it.I have gone through other answers but not sure.

文件夹结构

The problem is happening here:

    new File(metaInf.toURI())

If you look at the javadoc for the File(URI) constructor, it says:

Creates a new File instance by converting the given file: URI into an abstract pathname.

The problem is that the URLs / URIs provided by the getResources() enumerator are typically not file: URLs. If your code is executing out of a JAR file, or if there other JAR files on the classpath, then you could get jar: URLs. The File constructor cannot cope with them ... because the URLs don't name things with pathnames in the host filesystem.

In some cases, that would be the end of it. However, your case, you don't actually need to use File . Instead, you should be able to so something like this:

    BufferedReader br = new BufferedReader(
           new InputStreamReader(metaInf.openStream()));

The reason that this is running in Eclipse is that in that case the URLs will be file: URLs. The resources are accessed directly from the respective Eclipse workspace directories.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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