

大家好 為什么用buffered匯出的圖片是這樣的, 上面的圖片是原圖, 下面的是我匯出的 以下是我全部的代碼, 嫌麻煩可以直接看最下面我用=======隔開了,我試過word等其他檔案是沒有問題的,但是只要是圖片就會少內容,是我的代碼有問題嗎?
package upload;
import java.io.*;
import java.util.*;
public class PhotoUpload {
public void create() throws IOException {
File file = null;
boolean a = true;
do{
System.out.println("請輸入上傳的圖片路徑");
String element=new Scanner(System.in).next();
if(!element.endsWith(".jpg")&&!element.endsWith(".bmp")&&!element.endsWith(".png")){
System.out.println("圖片格式有誤,請重新輸入:");
continue;
}
file=new File(element);
if(!file.exists()&&!file.isDirectory()){
System.out.println("輸入地址不合法,請重新輸入:");
continue;
}
for (String s : new File("src/lib").list()) {
if(s.equals(file.getName())){
System.out.println("圖片已經存在,請重新輸入");
}else {
a=false;
}
}
}while (a);
try{
if(this.upload(file)){
System.out.println("圖片已經保存成功!");
}
}catch (Exception e){
System.out.println("圖片保存失敗!");
}
}
=====================================================================
//IO代碼
private boolean upload(File file) throws IOException {
BufferedInputStream bis=new BufferedInputStream(new FileInputStream(file));
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("src/lib/"+file.getName()));
int len;
while ((len=bis.read())!=-1){
bos.write(len);
}
bis.close();
bos.close();
return true;
}
}
uj5u.com熱心網友回復:
在bis.close();前加上bos.flush();否則輸出快取的資料還沒輸入完全檔案,輸出流就被關閉了。
uj5u.com熱心網友回復:
不是這個問題,我過了一會又運行了一遍代碼又好了
uj5u.com熱心網友回復:
就是這個問題,你自己谷歌百度一下輸出流flush的意義。即使你再運行不出錯,也只是偶然的,不能保證下次不出錯。要永遠消滅這個隱藏的bug,就是加flush。
你自己慢慢體會理解吧。
uj5u.com熱心網友回復:
我查一下看看轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/124597.html
標籤:Java SE
上一篇:SpringBoot jar包啟動之后一段時間 就僵死,無反應的問題。。。。
下一篇:代碼注釋
