如何复制Excel文件? [英] How to copy excel file?

查看:60
本文介绍了如何复制Excel文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用这种方法复制文件.它非常适合所有简单的文件类型,例如 csv txt pdf 等...除了 xlsx .我不知道为什么 Excel 文件不想被复制.它已损坏

I'm using this method to copy files . It works perfectly for all simple file types such as csv , txt , pdf etc . . . except xlsx. I don't know why Excel file doesn't want to be copied . It gets corrupted

public static void copyFileFromTo(File source, File dest)   {

    InputStream input = null;
    OutputStream output = null;

    try {
        input = new FileInputStream(source);
        output = new FileOutputStream(dest);
        byte[] buf = new byte[1024];
        int bytesRead;
        while ((bytesRead = input.read(buf)) > 0) {
        output.write(buf, 0, bytesRead); 
        }  
        input.close();
        output.close();
    }

    catch (IOException e) { 
    JOptionPane.showMessageDialog(null, e.getMessage() ); 
    System.exit(-1); 
 } 

} 

推荐答案

Excel文件实际上是ZIP文件(尝试在压缩程序中打开)-也许就是这个问题.我没有用Java编写代码,但建议您寻找一个ZIP复制例程-这是我在此处找到的一个例程:

Excel files are actually ZIP files (try opening in a compression program) - maybe that's the issue. I don't code in Java but I'd suggest looking for a ZIP copying routine - here's one I found on SO here: Best Way to copy a Zip File via Java

public final static int BUF_SIZE = 1024; //can be much bigger, see comment below


public static void copyFile(File in, File out) throws Exception {
  FileInputStream fis  = new FileInputStream(in);
  FileOutputStream fos = new FileOutputStream(out);
  try {
    byte[] buf = new byte[BUF_SIZE];
    int i = 0;
    while ((i = fis.read(buf)) != -1) {
        fos.write(buf, 0, i);
    }
  } 
  catch (Exception e) {
    throw e;
  }
  finally {
    if (fis != null) fis.close();
    if (fos != null) fos.close();
  }
}

由于对您不起作用,请尝试以下操作:

Since that didn't work for you try this: http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#copy%28java.nio.file.Path,%20java.nio.file.Path,%20java.nio.file.CopyOption...%29

import java.io.IOException;
import java.nio.file.*;

public class Program {
    public static void main(String[] args) {

        FileSystem system = FileSystems.getDefault();
        Path original = system.getPath("C:\\programs\\my.xlsx");
        Path target = system.getPath("C:\\programs\\my2.xlsx");

        try {
            // Throws an exception if the original file is not found.
            Files.copy(original, target, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException ex) {
            System.out.println("ERROR");
        }
    }
}

这篇关于如何复制Excel文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆