从服务器获取图像并保存到MySQL DB

时间:2014-11-12 16:44:16

标签: java mysql url ftp inputstream

我从服务器获取一个图像作为InputStream,然后将其保存到mySQL数据库。它在我使用Thread.sleep(5000);时有效。但是,如果我不使用它,没有图片保存到数据库或只有一张图片和一半或更少。所以我理解程序需要时间将图像写入数据库,但需要多长时间?这是一个问题,我想知道它何时完成将图像写入数据库并可以从下一个图像开始。以下是我的代码:

        ResultSet rs = stmt.executeQuery(query);
        while (rs.next()) {

            int ID = rs.getInt(1);
            String myName = rs.getString(2);

            try {

                String myCommand = "take picture and save /mydir/mydir2/mydir3" + myName + ".png";
                telnet.sendCommand(myCommand); // Here taking a picture via telnet
                // Thread.sleep(5000);// If I uncomment this line it works

                String sqlCommand = "UPDATE my_table SET Picture = ? WHERE ID ='" + ID +"';";
                PreparedStatement statement = conn.prepareStatement(sqlCommand);

                String ftpUrl = "ftp://"+server_IP+"/mydir/mydir2/mydir3" + myName + ".png;type=i";

                URL url = new URL(ftpUrl);
                URLConnection connUrl = url.openConnection();

                //Thread.sleep(5000); // If I uncomment this line, it works too.

                InputStream inputStreamTelnet = connUrl.getInputStream();

                statement.setBlob(1, inputStreamTelnet);
                int row = statement.executeUpdate();
                if (row > 0) {
                    System.out.println("A picture was inserted into DB.");
                    System.out.println("Value of row(s) : " + row);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        } // End of while

我希望在InputStream inputStreamTelnet = connUrl.getInputStream();之后放置等待(睡眠),但是当我在此行之后进行睡眠时它不起作用。它仅在睡眠之前有效。有人可以解释我为什么,我想避免使用Thread.sleep(5000);,而是想等待确切的时间或者不等待,这将使程序更快也可能有一个案例保存图片可能需要超过5秒或可能保存图片不需要时间但打开网址连接。当我取消其中一个程序工作时,代码上有2个睡眠行(成功将图像保存到mysql DB)。我还在服务器上验证了图像存在,但最后我在mysql DB中看不到它们。

更新:我删除了try块和telnet的东西,现在它无需等待,但我真的需要telnet的东西......

更新2:在检查我的telnet类后发现我忘了应用我对单行进行的更改...现在它无需等待就可以了!

1 个答案:

答案 0 :(得分:2)

嗯,我在JDK 1.7.0_67 / PostgreSQL 9.2上测试了我的代码并且运行良好:

public class ImageLoader {
    private static final int START_IMAGE_ID = 1;
    private static final int END_IMAGE_ID = 1000;

    private static final String IMAGE_URL = "http://savepic.net/%d.jpg";

    public static void main(String[] args) throws SQLException, IOException {
        Connection connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/test", "username", "password");
        PreparedStatement imageStatement = connection.prepareStatement("INSERT INTO public.image VALUES(?, ?)");

        for (int i = START_IMAGE_ID; i <= END_IMAGE_ID; i++) {
            String imageUrl = String.format(IMAGE_URL, i);

            URL url = new URL(imageUrl);
            URLConnection urlConnection = url.openConnection();

            imageStatement.setLong(1, i);
            imageStatement.setBytes(2, read(urlConnection.getInputStream()));

            int count = imageStatement.executeUpdate();
            if (count != 1) {
                throw new IllegalStateException("Image with ID = " + i + " not inserted");
            } else {
                System.out.println("Image (" + imageUrl + ") saved to database");
            }
        }

        imageStatement.close();
        connection.close();
    }

    private static byte[] read(InputStream inputStream) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1 << 15); // assume image average size ~ 32 Kbytes
        BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);

        byte[] buffer = new byte[1 << 10];

        int read = -1;
        while ((read = bufferedInputStream.read(buffer)) != -1) {
            byteArrayOutputStream.write(buffer, 0, read);
        }

        return byteArrayOutputStream.toByteArray();
    }
}