今有一项目采用struct2开发,用到了其中的上传文件功能,发现doc文件和图片文件上传都是正常的唯有office的docx版本文件上传发生错误。上传以后的docx能用office2007打开但是却提出文件格式错误的信息,经过与源文件进行对比发现上传后的文件多个10K而导致文件格式错误。经过检查发现是拷贝文件的时候发生错误
原先的拷贝文件的程序代码如下:
public void copy(File src, File dst) {
try {
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(src),
BUFFER_SIZE);
out = new BufferedOutputStream(new FileOutputStream(dst),
BUFFER_SIZE);
byte[] buffer = new byte[BUFFER_SIZE];
while (in.read(buffer) != -1) {
out.write(buffer);
}
} finally {
if (null != in) {
in.close();
}
if (null != out) {
out.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
现在改进为如下:
private static void copy(File src, File dst) {
try {
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(src),
BUFFER_SIZE);
out = new BufferedOutputStream(new FileOutputStream(dst),
BUFFER_SIZE);
byte[] buffer = new byte[BUFFER_SIZE];
int i = 0;
while ((i = in.read(buffer)) > 0) {
out.write(buffer, 0, i);
}
} finally {
if (null != out) {
out.close();
}
if (null != in) {
in.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}