读取jar内的文件?

时间:2013-02-03 05:06:55

标签: java file jar

我知道这已被问过多次,但我在这里遇到了问题。我希望能够逐行读取自定义文件类型,以便我可以执行保存和加载等操作。任何人都可以写一小段代码来告诉我如何做到这一点吗?

以下是我想阅读的内容:

//Here is where the code to get the file should be

while((String text = reader.readLine()) != null)
{
    if (text.startsWith("add"))
    //ect
}

3 个答案:

答案 0 :(得分:1)

Jar文件是ZIP文件,其中包含所有java编译的类文件和其他材料。要读取JAR文件中的文件,您必须能够读取zip文件。这里有一个例子:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class ReadZip {
  public static void main(String args[]) {
    try {
      ZipFile zf = new ZipFile("ReadZip.zip");
      Enumeration entries = zf.entries();

      BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
      while (entries.hasMoreElements()) {
        ZipEntry ze = (ZipEntry) entries.nextElement();
        System.out.println("Read " + ze.getName() + "?");
        String inputLine = input.readLine();   // your code here

 }
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

来自:http://www.java2s.com/Code/Java/File-Input-Output/ReadingtheContentsofaZIPFile.htm

答案 1 :(得分:1)

假设我们所讨论的jar是你的应用程序或你的应用程序的依赖项之一,这应该可行

BufferedReader br  = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(path)));

path - jar中文件的路径,例如“/test/test.txt的”

答案 2 :(得分:1)

要从jar资源打开文件,请参阅:Class#getResourceAsStream

读取文本文件的代码示例:

    try {
        InputStream in = getClass().getResourceAsStream("resource name"); // get binary stream to resource
        // InputStream in = new FileInputStream("filePath"); //in case file loaded from the FileSystem
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line = null;
        while ((line = reader.readLine()) != null)
        {
            if (line.startsWith("add")) {
                // e.t.c.
            }
        }
    }
    catch (IOException e) {
        //process exception or throw up
    }

使用Guava

从资源加载文件更容易
URL url = Resources.getResource(resourceName);
List<String> text = Resources.readLines(url, Charsets.UTF_8);