方法一:
public static void copy(File src, File des) throws IOException {
FileOutputStream writer = null;
FileInputStream reader = null;
BufferedInputStream bufR = null;
BufferedOutputStream bufW = null;
try {
reader = new FileInputStream(src);
writer = new FileOutputStream(des);
bufR = new BufferedInputStream(reader);
bufW = new BufferedOutputStream(writer);
int temp = 0;
while ((temp = bufR.read()) != -1) {
bufW.write(temp);
}
} catch (FileNotFoundException e) {
log.error(e.getMessage(), e);
} finally {
try {
if (bufR != null) {
reader.close();
bufR.close();
}
if (bufW != null) {
writer.close();
bufW.close();
}
} catch (IOException e) {
log.error("关闭连接失败", e);
}
}
}
这种方法复制excel会有部分格式丢失的问题
例如excel的批注以及颜色没有出来
方法二:
public static byte[] readFileToByteArray(String src) {
// 文件输入流(需要关闭)
InputStream is = null;
try {
is = new FileInputStream(new File(src));
// 字节数组输出流(不需要关闭)
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024 * 1];
int len;
while ((len = is.read(buf)) != -1) {
baos.write(buf, 0, len);
}
baos.flush();
return baos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
public static void writeByteArrayToFile(byte[] datas, String destFileName) {
// 文件输出流(需要关闭)
OutputStream os = null;
try {
// 字节数组输入流(不需要关闭)
InputStream is = new ByteArrayInputStream(datas);
os = new FileOutputStream(new File(destFileName));
byte[] buf = new byte[1024];
int len;
while (((len = is.read(buf)) != -1)) {
os.write(buf, 0, len);
}
os.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (os != null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
此方法能成功导出,先读再写。