简体   繁体   中英

Get Resource (in project root path) from jar file

I want to read a text file (input.txt) from within my running jar.

I did read a lot of similar questions, but none of them could help me with my specific problem.

The folder structure is something like that:

D:\\Users\\Nathaniel\\git\\projectfolder\\src\\main\\java\\folder1\\folder2\\files.java

My input.txt file is in the projectfolder.

And the main method is the files.java.

I did play around with all kinds of solutions: for example:

InputStream is = new FileInputStream("input.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(is));

Or:

Enumeration<URL> en = getClass().getClassLoader()
                .getResources("");
        List<String> profiles = new ArrayList<>();
        System.out.println("vor while");
        if (en.hasMoreElements()) {
            System.out.println("in while");
            URL url = en.nextElement();
            JarURLConnection urlcon = (JarURLConnection) (url.openConnection());
            try (JarFile jar = urlcon.getJarFile();) {
                Enumeration<JarEntry> entries = jar.entries();
                while (entries.hasMoreElements()) {
                    String entry = entries.nextElement().getName();
                    System.out.println(entry);
                }
            }
        }

Is there a solution that works when I run the program from eclipse AND the jar file?

Can you put your file in a resource folder (src/main/resources)? That way you could retrieve with:

BufferedReader reader = 
                new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/input.txt")));
        System.out.println(reader.readLine());
        reader.close();

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