จะอ่านไฟล์จากไฟล์เก็บถาวร JAR ได้อย่างไร [ทำซ้ำ]

ฉันต้องอ่านเนื้อหาของ /test/a.xml จากไฟล์ test.jar (แน่นอนว่าทั้งคู่เป็นตัวแปร ไม่ใช่ค่าคงที่) วิธีที่ง่ายที่สุดที่จะทำคืออะไร?

File file = new File("test.jar");
String path = "/test/a.xml";
String content = // ... how?

person yegor256    schedule 30.05.2013    source แหล่งที่มา
comment
แอปพลิเคชันของคุณทำงานจาก test.jar ด้วยหรือไม่   -  person Pshemo    schedule 30.05.2013
comment
ไม่ แอปพลิเคชันของฉันไม่ได้ทำงานจาก test.jar   -  person yegor256    schedule 30.05.2013
comment
คุณใช้จาวา 7 หรือไม่?   -  person Jimmy T.    schedule 30.05.2013
comment
คุณสามารถลองปรับตัวอย่างนี้: javaworld.com/javaworld/javatips/javatip49/ JarResources.java   -  person Hari Menon    schedule 30.05.2013


คำตอบ (2)


เป็นอย่างไรบ้าง:

JarFile file = new JarFile(new File("test.jar"));
JarEntry entry = file.getJarEntry("/test/a.xml");
String content = IOUtils.toString(file.getInputStream(entry));
person yegor256    schedule 30.05.2013

ใช้ ZipInputStream และค้นหาไฟล์ที่คุณต้องการ

FileInputStream fis = new FileInputStream(args[0]);
ZipInputStream zis =  new ZipInputStream(fis);
ZipEntry ze;

while ((ze = zis.getNextEntry()) != null)
   if(ze.getName().equals("/test/a.xml")
   {
       //use zis to read the file's content
   }
person Jimmy T.    schedule 30.05.2013
comment
จะใช้ zis เพื่ออ่านเนื้อหาของไฟล์ได้อย่างไร? - person mendel; 14.10.2020
comment
@mendel เมื่อคุณอยู่ในนั้นถ้าคุณสามารถใช้ fis เหมือนปกติ InputStream และมันจะให้เนื้อหาของไฟล์แก่คุณ - person Jimmy T.; 15.10.2020