nsIZipReader

Cette traduction est incomplète. Aidez à traduire cet article depuis l'anglais.

Cette interface fournit des méthodes pour la lecturedes fichiers compressés (zip) .
Inherits from: nsISupports Last changed in Gecko 10.0 (Firefox 10.0 / Thunderbird 10.0 / SeaMonkey 2.7)

Implemented by: @mozilla.org/libjar/zip-reader;1. To create an instance, use:

var zipReader = Components.classes["@mozilla.org/libjar/zip-reader;1"]
                .createInstance(Components.interfaces.nsIZipReader);

A propos des jeux de caractères et pages de codes

Note: nsIZipReader a un problème de page de code; dans la spécification ZIP, les noms de fichiers sont censés utiliser 7-bit ASCII; Cependant, la plupart des systèmes de fichiers modernes utilisent 8 bit de pages de codes, comme UTF-8. Cela peut désorganiser les caractères dans l'API nsIZipReader.

À partir de Gecko 10,0 (Firefox 10.0 / Thunderbird 10.0 / SeaMonkey 2.7), l'API nsIZipReader prend en charge de façon limité, 8 bits de page de code. Toutes les fonctions passent maintenant les noms de fichiers (dedans et dehors) en AUTF8String. Ainsi, vous pouvez désormais lire et extraire ce que vous avez écrit avec l'nsIZipWriter. Si vous comparez les noms de fichiers de findEntries() et de l'interface utilisateur, la mise en correspondance de caractères se base sur UTF-8 archives ZIP.

Aperçu des Méthode

void close();
void extract(in AUTF8String zipEntry, in nsIFile outFile);
void extract(in string zipEntry, in nsIFile outFile); Obsolète depuis Gecko 10
nsIUTF8StringEnumerator findEntries(in AUTF8String aPattern);
nsIUTF8StringEnumerator findEntries(in string aPattern); Obsolète depuis Gecko 10
nsIPrincipal getCertificatePrincipal(in AUTF8String aEntryName);
nsIPrincipal getCertificatePrincipal(in string aEntryName); Obsolète depuis Gecko 10
nsIZipEntry getEntry(in AUTF8String zipEntry);
nsIZipEntry getEntry(in string zipEntry); Obsolète depuis Gecko 10
nsIInputStream getInputStream(in AUTF8String zipEntry);
nsIInputStream getInputStream(in string zipEntry); Obsolète depuis Gecko 10
nsIInputStream getInputStreamWithSpec(in AUTF8String aJarSpec, in AUTF8String zipEntry);
nsIInputStream getInputStreamWithSpec(in AUTF8String aJarSpec, in string zipEntry); Obsolète depuis Gecko 10
boolean hasEntry(in AUTF8String zipEntry);
void init(in nsIFile zipFile); Obsolète depuis Gecko 1.9
void open(in nsIFile zipFile);
void openInner(in nsIZipReader zipReader, in AUTF8String zipEntry);
void openInner(in nsIZipReader zipReader, in string zipEntry); Obsolète depuis Gecko 10
void test(in AUTF8String aEntryName);
void test(in string aEntryName); Obsolète depuis Gecko 10

Attributs

Attribut Type Description
file nsIFile Le file qui représente le zip avec lequel ce lecteur zip a été initialisé. Lecture seule.
manifestEntriesCount PRUint32 Le nombre d'entrées dans le manifeste. Lecture seule.

Méthodes

close()

Ferme un lecteur zip. Les tentatives ultérieures d'extract() des fichiers ou lire à partir de son flux d'entrée se traduira par une erreur. Les tentatives ultérieures pour accéder à un nsIZipEntry obtenu à partir de ce lecteur zip va provoquer un comportement non spécifié.

void close();
Parameters

None.

Exemple pour démontrer cette fonction: Lister le contenu de XPI et Lire le Contenu du fichier

extract()

Extrait une entrée zip dans un file local spécifié par outFile. L'entrée doit être stocké dans le zip, dans un format non compressé ou DEFLATE-compressed pour que l'extraction soit couronnée de succès. Si l'entrée est un répertoire, le répertoire sera extrait de façon non-récursive.

void extract(
  in AUTF8String zipEntry,
  in nsIFile outFile
);
Parameters
zipEntry
L'entrée de zip à extraire.
outFile
La destination de fichier local utilisé pour extraire l'entrée de zip.

findEntries()

Renvoie un énumérateur de chaîne contenant les noms d'entrées correspondantes.

nsIUTF8StringEnumerator findEntries(
  in AUTF8String aPattern
);
Parameters
aPattern
A regular expression used to find matching entries in the zip file. Set this parameter to null (javascript) or EmptyCString() (c++) to get all entries; otherwise, use the following syntax:
  • * ne correspond à rien.
  • ? correspond à un caractère.
  • $ Correspond à la fin de la chaîne.
  • [abc] matches one occurrence of a, b, or c. The only character that must be escaped inside the brackets is ]. ^ and - must never appear in the first and second positions within the brackets, respectively. (In the former case, the behavior specified for '[^az]' will happen.)
  • [a-z] matches any character between a and z. The characters a and z must either both be letters or both be numbers, with the character represented by 'a' having a lower ASCII value than the character represented by 'z'.
  • [^az] matches any character except a or z. If ] is to appear inside the brackets as a character to not match, it must be escaped.
  • Pat~pat2 returns matches to the pattern 'pat' which do not also match the pattern 'pat2'. This may be used to perform filtering upon the results of one pattern to remove all matches which also match another pattern. For example, because '*' matches any string and '*z*' matches any string containing a 'z', '*~*z*' will match all strings except those containing a 'z'. Note that a pattern may not use '~' multiple times, so a string such as '*~*z*~*y*' is not a valid pattern.
  • (foo|bar) will match either the pattern foo or the pattern bar. Neither of the patterns foo or bar may use the 'pat~pat2' syntax described immediately above.
  • \ will escape a special character. Escaping is required for all special characters unless otherwise specified.
  • All other characters match case-sensitively.

 

An aPattern not conforming to this syntax has undefined behavior.

Return value

The nsIUTF8StringEnumerator containing the matching entry names.

Exceptions thrown
NS_ERROR_ILLEGAL_VALUE
On many but not all invalid aPattern values.

getCertificatePrincipal()

Returns an object describing the entity which signed an entry. parseManifest must be called first. If aEntryName is an entry in the jar, getInputStream() must be called after parseManifest. If aEntryName is an external file which has meta-information stored in the jar, verifyExternalFile (not yet implemented) must be called before getPrincipal.

nsIPrincipal getCertificatePrincipal(
  in string aEntryName
);
Parameters
aEntryName
Missing Description
Return value

An nsIPrincipal.

Example demonstrating this function: List Contents of XPI and Read File Contents

getEntry()

Returns a nsIZipEntry describing a specified zip entry.

nsIZipEntry getEntry(
  in AUTF8String zipEntry
);
Parameters
zipEntry
The zip entry.
Return value

The nsIZipEntry for the given zip entry.

Example demonstrating this function: List Contents of XPI and Read File Contents

getInputStream()

Returns an input stream containing the contents of the specified zip entry.

nsIInputStream getInputStream(
  in AUTF8String zipEntry
);
Parameters
zipEntry
The name of the entry to open() the stream from.
Return value

The nsIInputStream containing the contents of the specified zip entry.

Example demonstrating this function: List Contents of XPI and Read File Contents

getInputStreamWithSpec()

Returns an input stream containing the contents of the specified zip entry. If the entry refers to a directory (ends with '/'), a directory stream is opened, otherwise the contents of the file entry is returned.

nsIInputStream getInputStreamWithSpec(
  in AUTF8String aJarSpec,
  in AUTF8String zipEntry
);
Parameters
aJarSpec
The Spec of the URI for the JAR (only used for directory streams).
zipEntry
The name of the entry to open() the stream from.
Return value

The nsIInputStream containing the contents of the specified zip entry.

hasEntry()

Checks whether the zipfile contains an entry specified by zipEntry.

boolean hasEntry(
  in AUTF8String zipEntry
);
Parameters
zipEntry
The zip entry.
Return value

Boolean value, true if the zip entry exists, false is it does not exist.

init()

Obsolète depuis Gecko 1.9 (Firefox 3)

Initializes a zip reader after construction.

void init(
  in nsIFile zipFile
);
Parameters
zipFile
Zip file to initialize.

open()

Opens a zip file for reading. It is allowed to open with another file, but it needs to be closed first with close().

Note : Prior to Gecko 1.9 you first had to call init()"."

void open(
  in nsIFile zipFile 
);
Parameters
zipFile
The zip file to open.

Example demonstrating this function: List Contents of XPI and Read File Contents

openInner()

Opens a zip file inside a zip file for reading.

void openInner(
  in nsIZipReader zipReader, 
  in AUTF8String zipEntry
);
Parameters
 
zipReader
The zipReader object.
zipEntry
The zip entry.

test()

Tests the integrity of the archive by performing a CRC check on each item expanded into memory. If an entry is specified the integrity of only that item is tested. If null (javascript) or EmptyCString() (c++) is passed in the integrity of all items in the archive are tested.

void test(
  in AUTF8String aEntryName
);
Parameters
aEntryName
The single entity to check or null for checking all entries in the archive.

Examples

List contents of XPI and read file contents

This example uses findEntries, getEntry, getInputStream, open, and close. It also uses nsIScriptableInputStream to read the stream returned by getInputStream. XPI files are ZIP files, just Firefox needs the extension to be XPI. Change "PortableTester@jetpack.xpi" to the name of a XPI file in your extensions folder. Then you can copy and paste this code in scratchpad to run it.

    var zr = Cc["@mozilla.org/libjar/zip-reader;1"].createInstance(Ci.nsIZipReader);
    Cu.import('resource://gre/modules/osfile.jsm');
    Cu.import('resource://gre/modules/FileUtils.jsm');
    
    var reusableStreamInstance = Cc['@mozilla.org/scriptableinputstream;1'].createInstance(Ci.nsIScriptableInputStream);
    
    var pathToXpiToRead = OS.Path.join(OS.Constants.Path.profileDir, 'extensions', 'PortableTester@jetpack.xpi');
    var nsiFileXpi = new FileUtils.File(pathToXpiToRead);
    
    //Services.ww.activeWindow.alert(pathToXpiToRead);
    
    try {
      zr.open(nsiFileXpi); //if file dne it throws here
      var entries = zr.findEntries('*'); //we use asterik because we want EVERYTHING listed out
      while (entries.hasMore()) {
        var entryPointer = entries.getNext(); //just a string of "zip path" (this means path to file in zip, and it uses forward slashes remember)
        var entry = zr.getEntry(entryPointer); // should return true on `entry instanceof Ci.nsIZipEntry`
        console.log('entryPointer', entryPointer);
        /* CONSOLE OUTPUT
         * "entryPointer" "bootstrap.js" Scratchpad/1:18
         */
        console.info('entry', entry);
        /* CONSOLE OUTPUT
         * "entry" XPCWrappedNative_NoHelper { QueryInterface: QueryInterface(), compression: Getter, size: Getter, realSize: Getter, CRC32: Getter, isDirectory: Getter, lastModifiedTime: Getter, isSynthetic: Getter, permissions: Getter, compression: 8 } Scratchpad/1:19
         */
        if (!entry.isDirectory) {
            var inputStream = zr.getInputStream(entryPointer);
            reusableStreamInstance.init(inputStream);
            var fileContents = reusableStreamInstance.read(entry.realSize);
            console.log('contenst of file=', fileContents);
        } else {
            console.log('is directory, no stream to read');
        }
      }
    } catch (ex) {
      console.warn('exception occured = ', ex);
      if (ex.name == 'NS_ERROR_FILE_NOT_FOUND') {
        Services.ww.activeWindow.alert('XPI at path does not exist!\n\nPath = ' + pathToXpiToRead);
      }
    } finally {
      zr.close();
      console.log('zr closed');
    }

See also

Étiquettes et contributeurs liés au document

 Contributeurs à cette page : jmh
 Dernière mise à jour par : jmh,