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

问题描述:

我想写一个单元测试来测试从两个.doc文件创建.zip文件。 BU我需要一个错误:错误创建压缩文件:java.io.FileNotFoundException:d:\ FILE1.TXT(系统找不到指定的文件)如何从两个.doc文件创建一个.zip文件?

我的代码是在这里:

@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文件的名称来测试,如何理解通过测试?任何人都可以帮我解决这个错误吗?谢谢。

+0

我的猜测是,该文件是不存在或者路径是错误的(Windows使用'\'来分隔路径,你必须逃脱 – hotzst

+0

是否'd:?:\ file1.txt'存在做你有阅读权限吗?可能考虑尝试'D:\\ file1.txt' – CollinD

+0

我在D目录下创建了file1.txt和file2.txt文件,现在没有错误,但是我没有通过测试。定义目录:“D:\\ file1.txt”,“D:\ file1.txt”和“D:/file1.txt”。 – selentoptas

首先,您的文件是否在以前的测试方法中创建?如果是考虑到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()将返回类似:“[email protected]”,这将不等于“d :/ file.zip”。

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