开发者

How would I go about reading from a packaged file?

I have a file t开发者_Go百科hat I packaged in my JAR file, but I can't figure out how I would read the text file and store it into a String variable. Any ideas anyone?


I would recommend

java.lang.Class#getResource(java.lang.String) or java.lang.Class#getResourceAsStream(java.lang.String)


This approach would work for any jar file, even if it's not in your current project/library/classpath:

String myJarFilename ="C:\\path\\to\\myfile.jar";
JarFile jarFile = new JarFile(myJarFilename);
JarEntry jarEntry = jarFile.getJarEntry("mytextfile.txt");

if (jarEntry != null)
{
    InputStream is = jarFile.getInputStream(jarEntry);
    // do normal stuff here to read string from inputstream

    InputStreamReader isr = new InputStreamReader(is);
    byte[] charArr = new byte[2048];
    int bytesRead = 0;
    StringBuffer sb = new StringBuffer();
    while (bytesRead = is.read(charArr, 0, 2048) > 0)
    {
        sb.append(charArr, 0, bytesRead);            
    }
    String fileContent = sb.toString();
}


You can use a URLClassLoader to access resources in a JAR archive.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜