在做一个项目的时候遇到这样一个问题:
在网络上保存word文档的时候估计是出现了网络异常(一份不大的word文档
,保存的时候等了很久),然后再打开那份文件的时候就提示说“文件格式错误”。
检查源代码,摘录保存文件的部分代码如下:
public synchronized static int saveFileContent(HashMap hmp) throws Exception
{
byte[] body=(byte[])hmp.get("filebody");
FileOutputStream fos = null;
try
{
fos = new FileOutputStream(filePath + filename);
fos.write(body);
}
catch (IOException eIOe)
{
log.error("", eIOe);
}
finally
{
if (fos != null)
{
fos.flush();
fos.close();
fos = null;
}
}
}开始以为是fos.flush()的问题,以为把fos.flush();
从finally中调到try块中的fos.write(body)后可以解决
问题。但自己写了个小程序测试,结果并非如此,如下: String source = "D:\\project.doc";
String dest = "E:\\destination.doc";
File fIn = new File(source);
File fOut = new File(dest);
input = new FileInputStream(fIn);
output = new FileOutputStream(fOut);
byte[] buffer = new byte[1024];
int len = -1;
int loop = 0;
while((len=input.read(buffer))!=-1)
{
if(loop==12)
break;
output.write(buffer,0,len);
//loop++;
}
//output.flush();发现即使把 output.flush();注释掉,
文件一样写成功了。这里想请教一下:flush方法有什么用?如果我在写文件的过程中
出现错误,改如何恢复原来的文件?(相当于事务的回滚,撤销提交)。
在网络上保存word文档的时候估计是出现了网络异常(一份不大的word文档
,保存的时候等了很久),然后再打开那份文件的时候就提示说“文件格式错误”。
检查源代码,摘录保存文件的部分代码如下:
public synchronized static int saveFileContent(HashMap hmp) throws Exception
{
byte[] body=(byte[])hmp.get("filebody");
FileOutputStream fos = null;
try
{
fos = new FileOutputStream(filePath + filename);
fos.write(body);
}
catch (IOException eIOe)
{
log.error("", eIOe);
}
finally
{
if (fos != null)
{
fos.flush();
fos.close();
fos = null;
}
}
}开始以为是fos.flush()的问题,以为把fos.flush();
从finally中调到try块中的fos.write(body)后可以解决
问题。但自己写了个小程序测试,结果并非如此,如下: String source = "D:\\project.doc";
String dest = "E:\\destination.doc";
File fIn = new File(source);
File fOut = new File(dest);
input = new FileInputStream(fIn);
output = new FileOutputStream(fOut);
byte[] buffer = new byte[1024];
int len = -1;
int loop = 0;
while((len=input.read(buffer))!=-1)
{
if(loop==12)
break;
output.write(buffer,0,len);
//loop++;
}
//output.flush();发现即使把 output.flush();注释掉,
文件一样写成功了。这里想请教一下:flush方法有什么用?如果我在写文件的过程中
出现错误,改如何恢复原来的文件?(相当于事务的回滚,撤销提交)。
解决方案 »
- 请教坐标旋转排序的问题
- "找不到符号"的问题,大家帮忙看下
- JAVA反编译出来的方法看不懂,望高手讲解,在线等
- 编译Java程序出现:"Exception in thread "main" java.lang.NoClassDefFoundError: =" 错误,请问怎么回事,如何解决?
- 另一端的socket关闭后,这端怎么知道并处理?
- TreeSet中remove依据哪些方法来执行的?
- 关于JFrame移除组件时使用remove(Componet)和removeAll的问题
- 关于java socket的问题
- 如何使用 String 类的 equals 方法
- 简单GUI
- preparestatement的问题,高手请指教!
- 急..javabeans问题..50分求救啊
类似一下清除内存的概念
byte[] body,body就是这个内存空间咯?这样看来,是不是说如果出现我说的那个word文档
被破坏的情况,并不是写文件的时候出错,而是在
byte[] body=(byte[])hmp.get("filebody"); 的时候,
body取得的数据流就已经不对了?(因为那个项目是BS结构的),
偶想应该是网络造成数据丢失的可能性大些