2017-02-23 110 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); 
...