如何从两个 .doc 文件创建一个 .zip 文件?

How to create a .zip file from two .doc file?

我想编写一个单元测试来测试从两个 .doc 文件创建 .zip 文件。 BU 我报错:Error creating zip file: java.io.FileNotFoundException: D:\file1.txt (The system cannot find the file specified)

我的代码在这里:

@Test
public void testIsZipped() {

    String actualValue1 = "D:/file1.txt";
    String actualValue2 = "D:/file2.txt";

    String zipFile = "D:/file.zip";

    String[] srcFiles = { actualValue1, actualValue2 };

    try {

        // create byte buffer

        byte[] buffer = new byte[1024];

        FileOutputStream fos = new FileOutputStream(zipFile);
        zos = new ZipOutputStream(fos);

        for (int i = 0; i < srcFiles.length; i++) {

            File srcFile = new File(srcFiles[i]);

            FileInputStream fis = new FileInputStream(srcFile);

            // begin writing a new ZIP entry, positions the stream to the
            // start of the entry data

            zos.putNextEntry(new ZipEntry(srcFile.getName()));

            int length;

            while ((length = fis.read(buffer)) > 0) {

                zos.write(buffer, 0, length);
            }

            zos.closeEntry();

            // close the InputStream

            fis.close();
        }

        // close the ZipOutputStream

        zos.close();

    }

    catch (IOException ioe) {

        System.out.println("Error creating zip file: " + ioe);
    }

    String result = zos.toString();

    assertEquals("D:/file.zip", result);
}

能否从zos中获取zip文件名进行测试,如何理解才能通过测试?谁能帮我解决这个错误?谢谢。

首先,你的文件是用以前的测试方法创建的吗?如果是,请考虑 junit 测试不会按照您定义测试方法的顺序执行,请看一下:
How to run test methods in specific order in JUnit4?

其次,您可以添加调试行:

File srcFile = new File(srcFiles[i]);
System.out.append(srcFile+ ": " + srcFile.exists() + " " + srcFile.canRead());

解决异常后你会运行进入这个问题,测试会失败:

String result = zos.toString();

assertEquals("D:/file.zip", result);

zos.toString() 将 return 类似于:"java.util.zip.ZipOutputStream@1ae369b7" 不等于 "D:/file.zip".

String zipFile = "D:/file.zip";
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
System.out.println(zos.toString());