按目录中的组大小压缩文件

发布于 2024-12-04 20:44:57 字数 1030 浏览 0 评论 0原文

我有 2 个目录,必须打开并压缩其中的所有文件。我的问题是我的 zip 文件每个只能是 5MB,而且这些文件很大。在压缩这些文件之前,我必须了解如何按大小对这些文件进行分组。我想使用 Perl 的 Archive::Zip 模块来完成此操作。我有一些代码,但我想知道这里是否有人知道如何做到这一点,这是代码:

#!/perl/bin/perl -w
use strict;
use warnings;

use Archive::Zip qw/AZ_OK/;
use File::Temp qw/tempfile/;

use constant MB => 1024 * 1024;

#my @dir = '/dir1 dir2/';
my $dir = qw( dir1/);

my @files = do {
 opendir my $fd, "$dir" or die $! or die $!;
 grep -f, map  "$dir$_", readdir $fd;
};

my $zip = Archive::Zip->new;
my $total;
my $limit = 5*MB;



foreach my $file (@files) {

 my $temp = Archive::Zip->new;

 my $member = $temp->addFile($file);
 next unless $member->compressedSize;

 my $fh = tempfile();
 $temp->writeToFileHandle($fh) == AZ_OK or die $!;

 $zip->addMember($member);
 $total += $member->compressedSize;
 die "$total bytes exceeds archive size limit" if $total > $limit;

}

print "Total archive size: $total bytes\n\n";

$zip->writeToFileNamed('zipped.zip') == AZ_OK or die $!;

谢谢!

I have 2 directories that I have to open and zip all files in there. My issue is that my zip files can only be 5MB each, and these files are big. I have to some how group these files by size before zipping them. I would like to do this using Perl's Archive::Zip module. I have some code but I was wondering if someone here would know a way to do this, well here is the code:

#!/perl/bin/perl -w
use strict;
use warnings;

use Archive::Zip qw/AZ_OK/;
use File::Temp qw/tempfile/;

use constant MB => 1024 * 1024;

#my @dir = '/dir1 dir2/';
my $dir = qw( dir1/);

my @files = do {
 opendir my $fd, "$dir" or die $! or die $!;
 grep -f, map  "$dir$_", readdir $fd;
};

my $zip = Archive::Zip->new;
my $total;
my $limit = 5*MB;



foreach my $file (@files) {

 my $temp = Archive::Zip->new;

 my $member = $temp->addFile($file);
 next unless $member->compressedSize;

 my $fh = tempfile();
 $temp->writeToFileHandle($fh) == AZ_OK or die $!;

 $zip->addMember($member);
 $total += $member->compressedSize;
 die "$total bytes exceeds archive size limit" if $total > $limit;

}

print "Total archive size: $total bytes\n\n";

$zip->writeToFileNamed('zipped.zip') == AZ_OK or die $!;

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

寒江雪… 2024-12-11 20:44:57

恕我直言,你正在解决错误的问题。如果您需要将文件压缩成 5M 块,为什么不将它们全部压缩在一起,然后拆分成 5M 块呢?

您可以在 Perl 内部进行拆分(此处就是一个很好的例子);或者对于不太便携的解决方案,请使用系统命令 split(在 Unix/Linux 上可用;有一个 DOS 端口作为好吧

IMHO you are solving the wrong problem. If you need to zip the files into 5M chunks, why not zip them all together and then split into 5M chunks?

You can do the splitting internally to perl (a good example is here); or for less portable solution use a system command split (available on Unix/Linux; there's a DOS port as well)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文