【问题标题】:How to extract a single file from a zip archive in MATLAB?如何从 MATLAB 中的 zip 存档中提取单个文件?
【发布时间】:2016-06-02 12:24:23
【问题描述】:

单个文件unzip

MATLAB 中的unzip() 函数仅提供输入 zip 文件位置和输出目录位置的功能。有没有办法从 zip 存档中只提取一个文件而不是所有文件?

如果特定文件是已知的并且它是唯一需要的文件,这将减少提取文件的时间。

【问题讨论】:

    标签: matlab file unzip


    【解决方案1】:

    MATLAB 的unzip

    standard MATLAB function 无法做到这一点,但是...让我们破解该函数以使其执行所需的操作!

    MATLAB 的 unzip 单文件破解

    使用 MATLAB 的 unzip()extractArchive()(从 unzip() 调用)中的代码,可以创建一个自定义函数,仅从 zip 存档中提取单个文件。

    function [] = extractFile(zipFilename, outputDir, outputFile)
    % extractFile
    
    % Obtain the entry's output names
    outputName = fullfile(outputDir, outputFile);
    
    % Create a stream copier to copy files.
    streamCopier = ...
        com.mathworks.mlwidgets.io.InterruptibleStreamCopier.getInterruptibleStreamCopier;
    
    % Create a Java zipFile object and obtain the entries.
    try
        % Create a Java file of the Zip filename.
        zipJavaFile = java.io.File(zipFilename);
    
        % Create a java ZipFile and validate it.
        zipFile = org.apache.tools.zip.ZipFile(zipJavaFile);
    
        % Get entry
        entry = zipFile.getEntry(outputFile);
    
    catch exception
        if ~isempty(zipFile)
            zipFile.close;
        end
        delete(cleanUpUrl);
        error(message('MATLAB:unzip:unvalidZipFile', zipFilename));
    end
    
    % Create the Java File output object using the entry's name.
    file = java.io.File(outputName);
    
    % If the parent directory of the entry name does not exist, then create it.
    parentDir = char(file.getParent.toString);
    if ~exist(parentDir, 'dir')
        mkdir(parentDir)
    end
    
    % Create an output stream
    try
        fileOutputStream = java.io.FileOutputStream(file);
    catch exception
        overwriteExistingFile = file.isFile && ~file.canWrite;
        if overwriteExistingFile
            warning(message('MATLAB:extractArchive:UnableToOverwrite', outputName));
        else
            warning(message('MATLAB:extractArchive:UnableToCreate', outputName));
        end
        return
    end
    
    % Create an input stream from the API
    fileInputStream = zipFile.getInputStream(entry);
    
    % Extract the entry via the output stream.
    streamCopier.copyStream(fileInputStream, fileOutputStream);
    
    % Close the output stream.
    fileOutputStream.close;
    
    end
    

    【讨论】:

    • 我不会称之为“hack”,它是一个非常标准的 Java 解决方案。我过去创建了几乎相同的功能来实现所需的功能(之后我决定在项目中包含 7Zip 二进制文件并通过系统调用使用它):)
    • 同意,就 Java 这样的完整语言而言,这可能不是革命性的或骇人听闻的,但是从仅 MATLAB 的角度来看,它是对他们代码的破解(现有的接口/基础设施没有什么新东西是只是重用和重新安排做一些它不打算做的事情)。
    • @tmthydvnprt 您能否澄清一下代码delete(cleanUpUrl) 中的变量(或函数)cleanUpUrl 是什么?谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-15
    • 2015-04-02
    • 2012-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多