简体   繁体   English

我将如何读取打包的文件?

[英]How would I go about reading from a packaged file?

I have a file that 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. 我有一个打包在JAR文件中的文件,但是我不知道如何读取文本文件并将其存储到String变量中。 Any ideas anyone? 有任何想法吗?

This approach would work for any jar file, even if it's not in your current project/library/classpath: 这种方法适用于任何jar文件,即使它不在您当前的项目/库/类路径中:

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();
}

您可以使用URLClassLoader来访问JAR存档中的资源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 读取.txt文件。 我将如何读取整个字符串(忽略空格)并将其分配给on变量? - Reading .txt file. How would I go about just reading a whole string(ignoring spaces) & assigning it to on variable? 我想知道如何将其写入文件 - i was wondering how i would go about writing this to a file 如何将JAR文件复制到启动目录? - How would I go about copying the JAR file to the startup directory? 我将如何使用缓冲的读取器将.txt文件转换为ArrayList,以及如何处理该对象? - How would I use a buffered reader to convert a .txt file into an ArrayList and how would I go about manipulaing that object? 我将如何解析 Java 类文件常量池? - How would I go about parsing the Java class file constant pool? 我将如何在Java 8 Files API上实现与平台无关的文件爬网? - How would I go about implementing platform-agnostic file crawling on the Java 8 Files API? 如何从相对路径引用音频文件? - How would one go about referencing an audio file from a relative path? 我将如何从单链列表中的特定节点返回数据? - How would I go about returning the data from a specific node in a singly linked list? 我将如何从Java程序打印文本? (Java) - How would I go about printing text from a java program? (Java) 我将如何调用从单独的包中运行另一个类? - How would I go about calling in to run another class from a separate package?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM