2016-04-20 58 views
0

为什么当我尝试使用任何Writer实现来复制Excel文件的内容时,文件的内容被破坏! 。将xls文件从FileInputStream复制到FileWriter会破坏文件

@Test 
     public void testExcelCopy1() throws FileNotFoundException, IOException { 

      IOUtils.copy(new FileInputStream(new File("d:\\temp\\123.xls")), new OutputStreamWriter(
          new FileOutputStream("d:\\temp\\1234.xls"))); 

      Assert.assertArrayEquals(FileUtils.readFileToByteArray(new File("d:\\temp\\123.xls")) 
          , FileUtils.readFileToByteArray(new File("d:\\temp\\1234.xls"))); 
     } 

     @Test 
     public void testExcelCopy2() throws FileNotFoundException, IOException { 

      IOUtils.copy(new FileInputStream(new File("d:\\temp\\123.xls")), new FileOutputStream("d:\\temp\\12345.xls")); 

      Assert.assertArrayEquals(FileUtils.readFileToByteArray(new File("d:\\temp\\123.xls")) 
          , FileUtils.readFileToByteArray(new File("d:\\temp\\12345.xls"))); 
     } 

Test Result

我有一个reqiurement凡在我需要与Apache POI API创建的工作簿写入一个作家的实现!和我坚持这个问题!任何人都可以帮忙吗?

更新:

我明白的问题是,当我试图将一个字节流转换为字符流。但我不明白为什么。

此测试也失败!

@Test 
    public void testExcelCopy1() throws FileNotFoundException, IOException { 

     Reader reader = new InputStreamReader(new FileInputStream("d:\\temp\\123.xls")); 
     Writer write = new OutputStreamWriter(new FileOutputStream("d:\\temp\\1234.xls")); 
     IOUtils.copy(reader, write); 
     write.flush(); 
     write.close(); 

     Assert.assertArrayEquals(FileUtils.readFileToByteArray(new File("d:\\temp\\123.xls")) 
         , FileUtils.readFileToByteArray(new File("d:\\temp\\1234.xls"))); 
    } 
+0

因为你试图写一个字符为基础的API – Sanjeev

+0

二进制流这是否意味着没有办法,我可以做到这一点! 。我想将一个excel内容的字节数组写入Writer实现中。有没有其他方法?! 。 – Sagar

+0

您应该使用二进制流API来写入二进制数据。为什么需要将读写器的实现放在上面呢 – Sanjeev

回答

0

只要可能,IOUtils中的方法不会自行刷新或关闭流。调用者被认为负责关闭流。

请刷新并关闭流并尝试!

只要有可能,此类中的方法不会刷新或关闭 流。这是为了避免对流的起源和进一步使用做出不可移植的假设。因此,调用者仍然负责 用于在使用后关闭流。

https://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/IOUtils.html

+0

Thnx,这似乎不能解决问题。我不知道在excel内容的情况下,从byte数组转换为char数组是否存在任何问题!因为相同的文本文件工作正常。 – Sagar

0

我现在明白了它在技术上是不正确的尝试读取Excel或使用任何基于字符阅读器只适用于文本文件的任何其他OLE2对象的内容。我解决了我的问题。谢谢

底线是读者和作家只适用于txt,xml,json,csv等不适用于doc,xls或任何其他ms office文件。

不管怎样,谢谢你们

+1

很好,你找到它.. :) – Sanjeev