我有一堆 zip 文件夹,我必须提取并读取数据(存储在一个唯一的文件中)。问题是其中一些文件夹由于任何类型的错误而有两个同名文件(而不是 1 个)。当我使用 Matlab 命令“unzip”时,其中一个文件被另一个文件覆盖。问题是这两个文件不一样:其中一个包含我需要的信息,而另一个几乎是空的。所以我想将这两个文件重命名为file_a和file_b,然后提取它们,一旦两者都提取出来,只保留较大的一个。
您知道是否有任何方法可以重命名 zip 内的文件?
我创建了一个函数,可以修改 zip 文件内的文件名,以便可以无缝地解压缩它们。
该函数定位 zip 文件中的文件名,并将遇到的每个文件的第一个字母更改为序列“A、B、C、D 等...”。
function differentiateFileNames(zipFilename)
%% get the filenames contained in the zip file
filenames = getZipFileNames(zipFilename) ;
nFiles = numel(filenames) ;
%% Find the positions of the file name fields
% read the full file as a string
str = fileread(zipFilename) ;
% if all filenames are identical, we only need to search for the first name
% in our list
idx = strfind( str , filenames{1} ) ;
%% group indices by physical file
% Each filename appears twice in the zip file:
% ex for 2 files: file1 ... file2 ... file1 ...file2
idx = reshape(idx,nFiles,2)-1 ;
%% Now modify each filename
% (replace the first character of each filename)
fid = fopen(zipFilename,'r+') ;
for k=1:nFiles
char2write = uint8('A'+(k-1)) ; % will be: A, B, C, D, ect ...
fseek(fid,idx(k,1),'bof') ;
fwrite(fid,char2write,'uint8') ;
fseek(fid,idx(k,2),'bof') ;
fwrite(fid,char2write,'uint8') ;
end
fclose(fid) ;
end
function filenames = getZipFileNames(zipFilename)
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);
% Extract the entries from the ZipFile.
entries = zipFile.getEntries;
catch exception
if ~isempty(zipFile)
zipFile.close;
end
delete(cleanUpUrl);
error(message('MATLAB:unzip:invalidZipFile', zipFilename));
end
cleanUpObject = onCleanup(@()zipFile.close);
k = 0 ;
filenames = cell('') ;
while entries.hasMoreElements
k=k+1;
filenames{k,1} = char(entries.nextElement.getName) ;
end
zipFile.close
end
请注意,此脚本假定 zip 文件中的所有文件都具有相似的名称。当它找到文件名位置时,它仅检查找到的第一个文件名。
子功能
getZipFileNames
只是抄袭unzip.m
的部分内容,仅包含能够读取zip文件中包含的文件名所需的内容。
用于测试: 我制作了一个包含 2 个文件的 zip 文件:
New Text Document1.txt
New Text Document2.txt
我用十六进制编辑器修改了 zip 文件内的文件名,以便:
New Text Document1.txt
New Text Document1.txt
因此两个文件在存档中具有相同的名称。如果我尝试解压缩该文件,正如您所描述的,我只会在输出中得到一个文件(最后一个文件会覆盖另一个文件)。
如果我运行
differentiateFileNames(zipFilename)
,然后解压缩文件,我会在输出目录中得到 2 个文件:
Aew Text Document1.txt
Bew Text Document1.txt
我知道它看起来有点神秘,但它确保文件是有区别的。如果您愿意,作为练习,不需要太多扩展脚本即可直接unzip文件,找出最大的文件,删除另一个,然后使用正确的原始名称重命名剩下的文件。
我用7zip Manager 完成的,非常简单。 您可以进入 .zip 文件,然后右键单击 .zip 文件中的每个文件都有一个“重命名”选项。 问候。 玛丽亚