Snippet to create a file from the contents of a blob in Java

前端 未结 2 1521
半阙折子戏
半阙折子戏 2020-12-05 10:57

I have some files stored in a database blob column in Oracle 9.

I would like to have those files stored in the file system.

This should be pretty easy, but

2条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-05 11:48

    You'd want to get the blob as an inputstream and dump its contents to the outputstream. So 'misery' should be something like:

    Blob blob = rs.getBlob(column);
    InputStream in = blob.getBinaryStream();
    OutputStream out = new FileOutputStream(someFile);
    byte[] buff = new byte[4096];  // how much of the blob to read/write at a time
    int len = 0;
    
    while ((len = in.read(buff)) != -1) {
        out.write(buff, 0, len);
    }
    

    If you find yourself doing a lot of IO work like this, you might look into using Apache Commons IO to take care of the details. Then everything after setting up the streams would just be:

    IOUtils.copy(in, out);
    

提交回复
热议问题