2010-02-16 22 views
28

मेरे पास एक JAR फ़ाइल में एक फ़ाइल है। उदाहरण के लिए, यह है।एक जार फ़ाइल से फ़ाइल को कैसे पढ़ा जाए?

मैं इसे कैसे एक्सेस कर सकता हूं? मेरा स्रोत कोड है:

Double result=0.0; 
File file = new File("1.txt")); //how get this file from a jar file 
BufferedReader input = new BufferedReader(new FileReader(file)); 
String line; 
while ((line = input.readLine()) != null) { 
    if(me==Integer.parseInt(line.split(":")[0])){ 
    result= parseDouble(line.split(":")[1]); 
    } 
} 
input.close(); 
return result; 
+0

देख http://stackoverflow.com/questions को जार फ़ाइल से एक txt फ़ाइल कॉपी करने के लिए/16842306 – yegor256

+0

संभावित डुप्लिकेट [मैं जावा जार फ़ाइल से संसाधन फ़ाइल कैसे पढ़ूं?] (Http://stackoverflow.com/questions/403256/how-do-i-read-a-res ource-file-from-a-java-jar-file) – davecom

+0

संभावित डुप्लिकेट [जावा में जार से पढ़ने वाली फ़ाइल कैसे करें?] (http://stackoverflow.com/questions/3369794/how-to-a-read -फाइल-से-जार-इन-जावा) – Qix

उत्तर

27

आप फ़ाइल का उपयोग नहीं कर सकते, क्योंकि यह फ़ाइल फ़ाइल सिस्टम पर स्वतंत्र रूप से मौजूद नहीं है। इसके बजाय आप getResourceAsStream() की जरूरत है, तो जैसे:

... 
InputStream in = getClass().getResourceAsStream("/1.txt"); 
BufferedReader input = new BufferedReader(new InputStreamReader(in)); 
... 
+2

कॉलिंग क्लास मानना ​​जार फ़ाइल के अंदर है।अन्यथा वह इसे 'java.util.jar'' (या यहां तक ​​कि अधिक बुनियादी, 'java.util.zip' का उपयोग करके एक सादे पुरानी ज़िप फ़ाइल के रूप में) के वर्गों का उपयोग करके इसे पढ़ सकते हैं। –

4

कुछ this answer के समान है कि तुम क्या जरूरत है।

आपको फ़ाइल को उस विशेष तरीके से संग्रह से बाहर खींचने की आवश्यकता है।

BufferedReader input = new BufferedReader(new InputStreamReader(
     this.getClass().getClassLoader().getResourceAsStream("1.txt"))); 
+0

BufferedReader 'इनपुटस्ट्रीम' तर्क को छोड़कर नहीं करता – Bozho

+0

@ बोझो धन्यवाद, मेरे हिस्से पर थोड़ी सी निगरानी। – jjnguy

+0

मैं इस विधि के साथ बहुत फंस गया हूं धन्यवाद आपका तरीका काम करता है। –

46

अपने जार classpath पर हो:

URL url = new URL("jar:file:/absolute/location/of/yourJar.jar!/1.txt"); 
InputStream is = url.openStream(); 
+1

जार के बाद उस विस्मयादिबोधक बिंदु को भी शामिल करना सुनिश्चित करें। यह वैकल्पिक नहीं है। – hsmishka

+0

क्या इसका परीक्षण करने का कोई तरीका है? (जुनीट, टेस्टएनजी, स्पॉक, ... का उपयोग कर)। मैंने कोशिश की, लेकिन टेस्ट के दौरान फाइलें कभी नहीं मिलीं। – Edward

+0

आपके उत्तर के लिए धन्यवाद। यह हिस्सा "url.openStream();" मुझे क्या चाहिए था। – jmgoyesc

4

एक जार फ़ाइल एक ज़िप है:

InputStream is = YourClass.class.getResourceAsStream("1.txt"); 

यदि यह classpath पर नहीं है, तो आप इसके माध्यम से उपयोग कर सकते हैं फ़ाइल .....

तो एक जार फ़ाइल पढ़ने के लिए,

आज़माएं
ZipFile file = new ZipFile("whatever.jar"); 
if (file != null) { 
    ZipEntries entries = file.entries(); //get entries from the zip file... 

    if (entries != null) { 
     while (entries.hasMoreElements()) { 
      ZipEntry entry = entries.nextElement(); 

      //use the entry to see if it's the file '1.txt' 
      //Read from the byte using file.getInputStream(entry) 
     } 
    } 
} 

उम्मीद है कि इससे मदद मिलती है।

+0

अन्य उत्तरों सही हैं, मैंने अभी एक और विकल्प दिया है। –

0

मैंने कई बार पहले इस मुद्दे में भाग लिया है। मैं जेडीके 7 में उम्मीद कर रहा था कि कोई क्लासपाथ फाइल सिस्टम लिखेंगे, लेकिन अभी तक नहीं।

वसंत में संसाधन वर्ग है जो आपको क्लासपाथ संसाधनों को काफी अच्छी तरह से लोड करने की अनुमति देता है।

उत्तर बहुत अच्छे रहे हैं, लेकिन मैंने सोचा कि मैं एक उदाहरण दिखाने के साथ चर्चा में जोड़ सकता हूं जो क्लासपाथ संसाधनों वाली फ़ाइलों और निर्देशिकाओं के साथ काम करता है।

मैंने इस समस्या को हल करने के लिए एक छोटा प्रोटोटाइप लिखा था। प्रोटोटाइप प्रत्येक किनारे के मामले को संभाल नहीं करता है, लेकिन यह जार फ़ाइलों में निर्देशिकाओं में संसाधनों की तलाश में संभालता है।

मैंने कुछ समय के लिए स्टैक ओवरफ़्लो का उपयोग किया है। यह पहली बार है जब मुझे एक सवाल का जवाब याद है तो मुझे माफ़ कर दो अगर मैं लंबे समय तक जाऊं (यह मेरी प्रकृति है)।

 
    

    package com.foo; 

    import java.io.File; 
    import java.io.FileReader; 
    import java.io.InputStreamReader; 
    import java.io.Reader; 
    import java.net.URI; 
    import java.net.URL; 
    import java.util.Enumeration; 
    import java.util.zip.ZipEntry; 
    import java.util.zip.ZipFile; 

    /** 
    * Prototype resource reader. 
    * This prototype is devoid of error checking. 
    * 
    * 
    * I have two prototype jar files that I have setup. 
    * <pre> 
    *    <dependency> 
    *     <groupId>invoke</groupId> 
    *     <artifactId>invoke</artifactId> 
    *     <version>1.0-SNAPSHOT</version> 
    *    </dependency> 
    * 
    *    <dependency> 
    *     <groupId>node</groupId> 
    *     <artifactId>node</artifactId> 
    *     <version>1.0-SNAPSHOT</version> 
    *    </dependency> 
    * </pre> 
    * The jar files each have a file under /org/node/ called resource.txt. 
    * <br /> 
    * This is just a prototype of what a handler would look like with classpath:// 
    * I also have a resource.foo.txt in my local resources for this project. 
    * <br /> 
    */ 
    public class ClasspathReader { 

     public static void main(String[] args) throws Exception { 

      /* This project includes two jar files that each have a resource located 
       in /org/node/ called resource.txt. 
      */ 


      /* 
       Name space is just a device I am using to see if a file in a dir 
       starts with a name space. Think of namespace like a file extension 
       but it is the start of the file not the end. 
      */ 
      String namespace = "resource"; 

      //someResource is classpath. 
      String someResource = args.length > 0 ? args[0] : 
        //"classpath:///org/node/resource.txt"; It works with files 
        "classpath:///org/node/";     //It also works with directories 

      URI someResourceURI = URI.create(someResource); 

      System.out.println("URI of resource = " + someResourceURI); 

      someResource = someResourceURI.getPath(); 

      System.out.println("PATH of resource =" + someResource); 

      boolean isDir = !someResource.endsWith(".txt"); 


      /** Classpath resource can never really start with a starting slash. 
      * Logically they do, but in reality you have to strip it. 
      * This is a known behavior of classpath resources. 
      * It works with a slash unless the resource is in a jar file. 
      * Bottom line, by stripping it, it always works. 
      */ 
      if (someResource.startsWith("/")) { 
       someResource = someResource.substring(1); 
      } 

       /* Use the ClassLoader to lookup all resources that have this name. 
       Look for all resources that match the location we are looking for. */ 
      Enumeration resources = null; 

      /* Check the context classloader first. Always use this if available. */ 
      try { 
       resources = 
        Thread.currentThread().getContextClassLoader().getResources(someResource); 
      } catch (Exception ex) { 
       ex.printStackTrace(); 
      } 

      if (resources == null || !resources.hasMoreElements()) { 
       resources = ClasspathReader.class.getClassLoader().getResources(someResource); 
      } 

      //Now iterate over the URLs of the resources from the classpath 
      while (resources.hasMoreElements()) { 
       URL resource = resources.nextElement(); 


       /* if the resource is a file, it just means that we can use normal mechanism 
        to scan the directory. 
       */ 
       if (resource.getProtocol().equals("file")) { 
        //if it is a file then we can handle it the normal way. 
        handleFile(resource, namespace); 
        continue; 
       } 

       System.out.println("Resource " + resource); 

       /* 

       Split up the string that looks like this: 
       jar:file:/Users/rick/.m2/repository/invoke/invoke/1.0-SNAPSHOT/invoke-1.0-SNAPSHOT.jar!/org/node/ 
       into 
        this /Users/rick/.m2/repository/invoke/invoke/1.0-SNAPSHOT/invoke-1.0-SNAPSHOT.jar 
       and this 
        /org/node/ 
       */ 
       String[] split = resource.toString().split(":"); 
       String[] split2 = split[2].split("!"); 
       String zipFileName = split2[0]; 
       String sresource = split2[1]; 

       System.out.printf("After split zip file name = %s," + 
         " \nresource in zip %s \n", zipFileName, sresource); 


       /* Open up the zip file. */ 
       ZipFile zipFile = new ZipFile(zipFileName); 


       /* Iterate through the entries. */ 
       Enumeration entries = zipFile.entries(); 

       while (entries.hasMoreElements()) { 
        ZipEntry entry = entries.nextElement(); 
        /* If it is a directory, then skip it. */ 
        if (entry.isDirectory()) { 
         continue; 
        } 

        String entryName = entry.getName(); 
        System.out.printf("zip entry name %s \n", entryName); 

        /* If it does not start with our someResource String 
         then it is not our resource so continue. 
        */ 
        if (!entryName.startsWith(someResource)) { 
         continue; 
        } 


        /* the fileName part from the entry name. 
        * where /foo/bar/foo/bee/bar.txt, bar.txt is the file 
        */ 
        String fileName = entryName.substring(entryName.lastIndexOf("/") + 1); 
        System.out.printf("fileName %s \n", fileName); 

        /* See if the file starts with our namespace and ends with our extension.   
        */ 
        if (fileName.startsWith(namespace) && fileName.endsWith(".txt")) { 


         /* If you found the file, print out 
          the contents fo the file to System.out.*/ 
         try (Reader reader = new InputStreamReader(zipFile.getInputStream(entry))) { 
          StringBuilder builder = new StringBuilder(); 
          int ch = 0; 
          while ((ch = reader.read()) != -1) { 
           builder.append((char) ch); 

          } 
          System.out.printf("zip fileName = %s\n\n####\n contents of file %s\n###\n", entryName, builder); 
         } catch (Exception ex) { 
          ex.printStackTrace(); 
         } 
        } 

        //use the entry to see if it's the file '1.txt' 
        //Read from the byte using file.getInputStream(entry) 
       } 

      } 


     } 

     /** 
     * The file was on the file system not a zip file, 
     * this is here for completeness for this example. 
     * otherwise. 
     * 
     * @param resource 
     * @param namespace 
     * @throws Exception 
     */ 
     private static void handleFile(URL resource, String namespace) throws Exception { 
      System.out.println("Handle this resource as a file " + resource); 
      URI uri = resource.toURI(); 
      File file = new File(uri.getPath()); 


      if (file.isDirectory()) { 
       for (File childFile : file.listFiles()) { 
        if (childFile.isDirectory()) { 
         continue; 
        } 
        String fileName = childFile.getName(); 
        if (fileName.startsWith(namespace) && fileName.endsWith("txt")) { 

         try (FileReader reader = new FileReader(childFile)) { 
          StringBuilder builder = new StringBuilder(); 
          int ch = 0; 
          while ((ch = reader.read()) != -1) { 
           builder.append((char) ch); 

          } 
          System.out.printf("fileName = %s\n\n####\n contents of file %s\n###\n", childFile, builder); 
         } catch (Exception ex) { 
          ex.printStackTrace(); 
         } 

        } 

       } 
      } else { 
       String fileName = file.getName(); 
       if (fileName.startsWith(namespace) && fileName.endsWith("txt")) { 

        try (FileReader reader = new FileReader(file)) { 
         StringBuilder builder = new StringBuilder(); 
         int ch = 0; 
         while ((ch = reader.read()) != -1) { 
          builder.append((char) ch); 

         } 
         System.out.printf("fileName = %s\n\n####\n contents of file %s\n###\n", fileName, builder); 
        } catch (Exception ex) { 
         ex.printStackTrace(); 
        } 

       } 

      } 
     } 

    } 


 

You can see a fuller example here with the sample output.

1

यह मेरे लिए काम किया एक और txt फ़ाइल

public static void copyTextMethod() throws Exception{ 
    String inputPath = "path/to/.jar"; 
    String outputPath = "Desktop/CopyText.txt"; 

    File resStreamOut = new File(outputPath); 

    int readBytes; 
    JarFile file = new JarFile(inputPath); 

    FileWriter fw = new FileWriter(resStreamOut); 

    try{ 
     Enumeration<JarEntry> entries = file.entries(); 
     while (entries.hasMoreElements()){ 
      JarEntry entry = entries.nextElement(); 
     if (entry.getName().equals("readMe/tempReadme.txt")) { 

       System.out.println(entry +" : Entry"); 
      InputStream is = file.getInputStream(entry); 
      BufferedWriter output = new BufferedWriter(fw); 
       while ((readBytes = is.read()) != -1) { 
        output.write((char) readBytes); 
       } 
       System.out.println(outputPath); 
       output.close(); 
      } 
     } 
    } catch(Exception er){ 
     er.printStackTrace(); 
    } 
     } 
      } 
-1
InputStream inputStreamLastName = this.getClass().getClassLoader().getResourceAsStream("path of file"); 


    try { 

     br = new BufferedReader(new InputStreamReader(inputStreamLastName, "UTF-8")); 
     String sCurrentLine; 
     ArrayList<String> lastNamesList = new ArrayList<String>(); 
     while ((sCurrentLine = br.readLine()) != null) { 

      if(sCurrentLine.length()>=min && sCurrentLine.length()<=max){ 
       lastNamesList.add(sCurrentLine); 
      } 

     } 
+0

इस मुद्दे के जवाब के साथ कुछ स्पष्टीकरण जोड़ें कि इस मुद्दे को वर्तमान समस्या को ठीक करने में ओपी की मदद कैसे करें –

2
private String loadResourceFileIntoString(String path) { 
    //path = "/resources/html/custom.css" for example 
    BufferedReader buffer = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(path))); 
    return buffer.lines().collect(Collectors.joining(System.getProperty("line.separator"))); 
} 
संबंधित मुद्दे