如何从MATLAB中的zip存档中提取单个文件?

时间:2016-06-02 12:24:23

标签: matlab file unzip

单个文件unzip

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

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

1 个答案:

答案 0 :(得分:4)

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