今有一项目采用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();
}
}
文章详细介绍了在使用struct2开发时遇到的问题,即上传的Office docx文件在打开时出现格式错误。通过分析,发现问题是由于在复制文件过程中发生的错误导致的大小变化。文章提供了改进的文件复制程序代码来解决此问题。
228

被折叠的 条评论
为什么被折叠?



