“嗨,阿米戈!”

“嗨,艾莉!”

“今天我们要研究I/O流。”

“是的,我已经对它们一清二楚了。我们这里使用的是FileInputStream和FileOutputStream类。”

“是的,你知道这些课程中的哪些方法?”

“当然。这是 FileInputStream 的方法:”

方法 描述
int read() 读取一个字节并返回它。
int read(byte b[]) 读取一个字节数组并返回它。
int read(byte b[], int off, int len) 从流中读取字节数组。
long skip(long n) 跳过 n 个字节,从流中读取时使用。
int available() 返回仍可从流中读取的字节数。
void close() 关闭流。

“没错!还有 FileOutputStream 的方法?”

“看一看:”

方法 描述
void write(int b) 向流中写入一个字节。
void write(byte b[]) 将字节数组写入流。
void write(byte b[], int off, int len) 将字节数组写入流。
void close() 关闭流。

“阿米戈,你让我惊喜!”

“然后还有一些!”

“好吧,那我给你两个新类:ZipInputStream 和 ZipOutputStream。”

文件输入流、文件输出流、ZipOutputStream、ZipInputStream - 1

Zip?那是像 zip 文件吗?”

“完全正确。这些流设计用于处理 zip 文件。您可以使用它们直接读取或写入 zip 文件!”

“我的天啊!真有趣。但是一个 zip 文件不能有一个文件,而是多个文件。它们是如何工作的?”

“为此,还有另一个特殊的类:ZipEntry。它提供了一个存储在存档中的文件。您只能从ZipInputStream读取ZipEntry对象,并且只能将ZipEntry对象写入ZipOutputStream。但事实证明您可以读取和像写入普通文件一样写入ZipEntry 。”

“你能举个例子说明它是如何工作的吗?”

“当然。这是一个我们创建存档并将文件放入其中的示例:”

代码
// Create an archive
FileOutputStream zipFile = new FileOutputStream("c:/archive.zip");
ZipOutputStream zip = new ZipOutputStream(zipFile);

//Put a ZipEntry into it
zip.putNextEntry(new ZipEntry("document.txt"));

//Copy the file «document-for-archive.txt» to the archive under the name «document.txt»
File file = new File("c:/document-for-archive.txt");
Files.copy(file.toPath(), zip);

// Close the archive
zip.close();

“多么有趣!解压缩文件也一样简单吗?”

“是的。这里是ZipEntryZipInputStream  和ZipOutputStream类方法的简要说明”

ZipInputStream是一个流,所以所有的ZipEntry只能顺序读取。下面是它的方法:”

方法 描述
ZipEntry getNextEntry() 返回描述下一个 ZipEntry 的对象(跳过当前条目中的所有字节)。
void closeEntry() 关闭当前 ZipEntry 上的输入流(跳过当前条目中的所有字节)。
int available() 返回 1 有可用的 ZipEntries,否则返回 0。
int read(byte[] b, int off, int len) 从当前 ZipEntry 读取字节。
long skip(long n) 从流中读取时跳过 n 个字节。
void close() 关闭流。

“我不太明白。”

“最好的办法是想象你正在阅读一个文本文件,而 ZipEntries 就像文件中的行。你可以从当前行(当前 ZipEntry 读取数据或从一行跳到另一行(getNextEntrycloseEntry) ”

“我想我明白了,但我不确定。”

“这是 ZipOutputStream 及其方法:”

方法 描述
void setComment(String comment) 设置对存档的评论。
void setMethod(int method) 设置压缩方法(类型)。
void setLevel(int level) 设置压缩级别。压缩越高,速度越慢。
void putNextEntry(ZipEntry e) 添加一个新的 ZipEntry。
void closeEntry() 关闭当前的 ZipEntry
void write(byte[] b, int off, int len) 将一组字节写入当前 ZipEntry。
void close() 关闭流。

“但在上面的例子中,我们几乎没有使用这些。”

“这些是可选方法。您不必指定压缩级别和方法——将使用默认设置。”

“嗯。还不错。ZipEntry 呢?”

“当然。ZipEntry 中唯一的其他信息是管理信息:”

方法 描述
String getName(), setName(String) 内部名称文件。
long getTime(), setTime(long) 上次修改条目的时间。
long getCRC(), setCRC(long) 校验和。
long getSize(), setSize(long) 压缩前的大小。
int getMethod(), setMethod(int) 压缩方法。
long get/setCompressedSize() 压缩后尺寸。
boolean isDirectory() 条目是目录吗?

“这看起来并不难。有什么可以不去爱的!”

“太好了,那迪亚哥也给你布置这方面的任务。”

“我应该闭嘴。”