Reading a text file from a jar

前端 未结 3 906
慢半拍i
慢半拍i 2020-12-07 06:07

I\'m having trouble reading a text file from inside a jar. I managed it while it was unzipped but now that I\'ve archived it it won\'t work. The jar has:

  • BTA.j
相关标签:
3条回答
  • 2020-12-07 06:20

    Assuming you're executing the BTA.jar, you can use

    InputStream in = YourClass.class.getResourceAsStream("/Splash.txt");
    

    to retrieve an InputStream and pass it to the BufferedReader through an InputStreamReader.

    The rules for the format of the path to pass to the method are defined here, in the javadoc for the Class class.

    0 讨论(0)
  • 2020-12-07 06:21

    A jar is just a zip file and can be read like this..

    ZipFile file = new ZipFile("/home/Desktop/myjar.jar");
    Enumeration<? extends ZipEntry> entries = file.entries();
    
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
    
        if (entry.getName().startsWith("splash")) {
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream(entry)))) {
                String line = null;
                while ((line = reader.readLine()) != null) {
                    System.out.println(line);
                }
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-07 06:44

    The problem is Splash.txt isn't a file, its series of bytes within in a (lightly) compressed file which has a named entry within a table of contents as specified by the Jar/Zip standard.

    This measn you can use FileReader to read the file, instead, you need to access it via the Class resource management API, for example..

    getClass().getResourceAsStream("/Splash.txt");
    

    Or, if you're trying to read it from static context

    Splash.class.getResourceAsStream("/Splash.txt");
    

    Don't forget, you become responsible for closing the InputStream when you are done, for example...

    try (InputStream is = getClass().getResourceAsStream("/Splash.txt")) {....
    
    0 讨论(0)
提交回复
热议问题