john john - 4 months ago 31
Java Question

How to copy excel file?

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);
}

}

Answer

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");
        }
    }
}
Comments