0

我正在开发一个需要经常访问 zip 文件以添加、删除和读取文件的应用程序。我正在考虑使用 truezip,因为它保证我可以相当轻松地完成所有这些工作(能够传递并从当前压缩的文件中读取是它提供的最大优势)但是在使用它时我无法将文件添加到档案。我的代码:

public void testfunction()
{
    //below create the archive if it doesn't exist
    TFile tFile = new TFile("src\\test\\resources\\archiveTest\\demoZip.zip");
    if (!tFile.exists()) // I get an EOFException here
    {
        tFile.createNewFile();
    }

    TFile innerFile = new TFile("src\\test\\resources\\archiveTest\\demoZip.zip\\someText.txt");
    innerFile.createNewFile(); // also here

    BufferedWriter out = new BufferedWriter(new FileWriter(innerFile));

    out.write("demo text");
    out.close(); // I know this is bad
}

当我运行它时,无论我如何尝试安排这个简单的事情,我都会得到一个 java.io.EOFException 。如果我尝试确保文件已经创建,我只会在调用 tFile.exists() 方法时得到异常。如果我不这样做,那么当我稍后尝试创建 innerFile 时就会得到它(即使 zip 文件已经存在)。

我应该注意:truezip 原型中的示例使用 TApplication 类,但我不能这样做。我必须能够开箱即用地使用这个库。我无法更改应用程序的结构,因此使应用程序本身成为 TApplication 子类不是一个可行的解决方案(尽管我可以根据需要更改调用类的结构)。

目前我的 POM 包括这些依赖项(包括在我找到的示例中):

<dependency>
    <groupId>de.schlichtherle.truezip</groupId>
    <artifactId>truezip-file</artifactId>
    <version>7.4.1</version>
</dependency>
<dependency>
    <groupId>de.schlichtherle.truezip</groupId>
    <artifactId>truezip-driver-zip</artifactId>
    <version>7.4.1</version>
</dependency>
    <dependency>
    <groupId>de.schlichtherle.truezip</groupId>
    <artifactId>truezip-kernel</artifactId>
    <version>7.4.1</version>
</dependency>
<dependency>
    <groupId>de.schlichtherle.truezip</groupId>
    <artifactId>truezip-driver-file</artifactId>
    <version>7.4.1</version>
</dependency>

所以我不知道我在做什么,所以我能得到的任何建议都会受到赞赏,因为互联网上的大多数例子似乎都假设比我拥有更多的知识。

4

1 回答 1

0

你的 POM 设置看起来是正确的,所以这样的事情应该可以工作:

public void testfunction()
{
    TFile innerFile = new TFile("src/test/resources/archiveTest/demoZip.zip/someText.txt");

    BufferedWriter out = new BufferedWriter(new FileWriter(innerFile));
    try {
        out.write("demo text");
    } finally {
        out.close();
    }
}

请注意,存档文件是一个虚拟目录,因此为了创建一个,您将调用 TFile.mkdir(),而不是 TFile.createNewFile()。但是,无需先创建存档文件。如果它尚不存在,它将自动创建。

使用项目的 Maven 原型时​​,您可以找到更多示例:http: //truezip.java.net/kick-start/index.html

PS:TrueZIP 7.4.2 已经发布——请更新你的依赖。

于 2011-12-13T23:52:48.347 回答