解决Struts2上传docx文件变大的问题
2016-01-22 01:02
513 查看
今有一项目采用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();
}
}
原先的拷贝文件的程序代码如下:
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();
}
}
相关文章推荐
- Java基础_13_反射机制
- JAVA中String类的intern()方法的作用
- Java排序: Comparator vs Comparable 入门
- java中的JTable类
- Spring Boot 使用Java代码创建Bean并注册到Spring中
- spring框架学习--依赖注入
- @Index用法——javax.persistence.Index
- Java类初始化顺序
- 为Java说句公道话
- JAVA Web防止表单重复提交实例
- Java获取当前时间的年月日方法
- java和jdk的那些事
- Spring注解注解解析
- SpringMVC参数绑定---对象绑定
- android studio使用教程(九)eclipse工程导入studio中乱码解决方案
- Lombok 注解说明
- 使用Spring AOP中MethodInterceptor记录日志
- spring整合jms
- Java HashMap vs HashTable
- Eclipse and test packages now in white and un-run