2017-02-23 107 views
0

我試圖從數據庫檢索圖像並將其添加到Person類。我通過Files.copy()將圖像複製到新圖像文件並設置新的圖像對象。但是,似乎每個複製的所有過程都是從第一個開始的,所以所有的Image對象都只有一個圖像 - 最後複製的圖像,但copy()方法在之前設置。如何解決它?Files.copy方法工作不正常

try { 
    checkConnection(); 
    rs = con.prepareStatement("SELECT * FROM Staff").executeQuery(); 

    while(rs.next()){ 
     InputStream is = rs.getBinaryStream("Photo"); 
     Files.copy(is, Paths.get("src\\ilc\\images\\image.jpg"), StandardCopyOption.REPLACE_EXISTING); 
     Image image = new Image("ilc/images/image.jpg", 100, 100, true, true); 

     Rectangle rectangle = new Rectangle(); 
     persons.add(
       new Person(rs.getString("Name"), 
          rs.getInt("Salary"), 
          rs.getDouble("Influence"), 
          false, 
          false, 
          false, 
          image) 
     ); 
    } 

    rs.close(); 
} 
catch (FileNotFoundException ex) { 
    ex.printStackTrace(); 
} 
catch (SQLException ex) { 
    ex.printStackTrace(); 
} 
catch (IOException ex) { 
    ex.printStackTrace(); 
} 
+0

爲什麼不ü要創建的InputStream圖片,你有'後的InputStream is = rs.getBinaryStream(「Photo」);'?你根本不需要使用'Files.copy'。 – Enigo

+0

你是天才的人!有用!非常感謝! :D –

+0

太棒了,很高興它的工作。我發佈它作爲答案,所以我們可以關閉你的問題) – Enigo

回答

0

在這種情況下,解決辦法是不使用Files.copy在所有和創建Image使用InputStream直接:

InputStream is = rs.getBinaryStream("Photo"); 
Image image = new Image(is, 100, 100, true, true); 
...