【问题标题】:Files.copy method works unproperlyFiles.copy 方法工作不正常
【发布时间】:2017-02-23 17:41:20
【问题描述】:

我试图从数据库中检索图像并将其添加到类 Person。我通过 Files.copy() 将图像复制到新的图像文件并设置新的 Image 对象。但似乎每次复制的所有过程都是首先开始的,所以所有的 Image 对象都只有一个图像 - 最后一个复制的图像,但是 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();
} 

【问题讨论】:

  • 你为什么不想用 InputStream is = rs.getBinaryStream("Photo"); 之后的 InputStream 创建图像?你根本不需要使用Files.copy
  • 你是天才!有用!太感谢了! :D
  • 太好了,很高兴它成功了。我将其发布为答案,以便我们可以结束您的问题)

标签: image file javafx stream copy


【解决方案1】:

在这种情况下,解决方案是根本不使用Files.copy,而是直接使用InputStream 创建Image

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

【讨论】:

    猜你喜欢
    • 2016-08-01
    • 2012-11-08
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    • 2015-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多