作者andyliu (迈向欧啪之路)
看板java
标题[奇文共赏] JAVA 复制档案问题
时间Wed Sep 17 01:29:58 2008
刚刚在找资料的时候瞄到一篇blog文章,阅後大惊,转录一下
------------------------------------------------------
这麽多年了,我一直使用下列的程式码在处理java 搬档问题
fis = new FileInputStream(file);
fos = new FileOutputStream(file1);
byte fileBuffer[] = new byte[512];
int fileIdx = -1;
while ((fileIdx = fis.read(fileBuffer)) != -1) {
fos.write(fileBuffer);
}
有时会发生excel档或是pdf档上传後不能开启,
後来发现用fos.write(fileBuffer,0,fileIdx);这个方法是可以解决的,
应该就是只写入这次截取的长度,而不是写入buffer的长度.
------------------------------------------------------
出处就不附了(反正随便google也找的到),免得搞成我好像故意在鞭他一样...
我大惊的原因是怎会有一个多年经验的程式设计师会犯这种错,实在很夸张呀!!
况且,如果照他文内所述是"搬档",也不是用这个方法呀...XD
不过後来看到这段 code, from
http://caterpillar.onlyfun.net/Gossip/JavaGossip-V2/FileInOutStream.htm
------------------------------------------------------
byte[] buffer = new byte[1024];
FileInputStream fileInputStream =
new FileInputStream(new File(args[0]));
FileOutputStream fileOutputStream =
new FileOutputStream(new File(args[1]));
System.out.println("复制档案:" +
fileInputStream.available() + "位元组");
while(true) { // 从来源档案读取资料至缓冲区
int length = fileInputStream.read(buffer);
if(length == buffer.length) {
// 将阵列资料写入目的档案
fileOutputStream.write(buffer);
}
else {
byte[] buf = new byte[length];
System.arraycopy(buffer, 0, buf, 0, length);
fileOutputStream.write(buf);
break;
}
}
// 关闭串流
fileInputStream.close();
fileOutputStream.close();
System.out.println("复制完成");
------------------------------------------------------
就觉得 OutputStream 的 write(byte[] b, int off, int len) 好可怜,
好像真的很讨人厌,都没有人爱用它...XD
为什麽要搞出这种脱裤子放屁的行为呢? 真难理解...
而且 InputStream available() 的原意应该不是这样用的,只是恰巧在
读取档案时,刚好等於档案大小而已。
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 140.112.30.32
1F:推 GALINE:当api太多时,很容易难以看清全貌…吧 09/18 00:39
2F:推 JustinHere:学艺不精,感谢指正。。。Orz.... 09/18 14:42
3F:推 slalala:感谢原PO解决我去年在"搬运" *.mdb档案时出错的困惑Orz 10/11 00:27