有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在文件中写入数据

我发现了这个如何从PostgreSQL读取二进制文件的示例

conn.setAutoCommit(false);

        // Get the Large Object Manager to perform operations with
        LargeObjectManager lobj = ((org.postgresql.PGConnection) conn).getLargeObjectAPI();

        ps = conn.prepareStatement("SELECT FILE FROM KNOWLEDGEBASE_FILES WHERE ID = ?");
        ps.setInt(1, 333);
        ResultSet rs = ps.executeQuery();
        while (rs.next())
        {
            // Open the large object for reading
            long oid = rs.getLong(1);
            LargeObject obj = lobj.open(oid, LargeObjectManager.READ);

            // Read the data
            byte buf[] = new byte[obj.size()];
            obj.read(buf, 0, obj.size());
            // Do something with the data read here


            FileChannel rwChannel = new RandomAccessFile("License_Agreement.pdf", "rw").getChannel();
            ByteBuffer wrBuf = rwChannel.map(FileChannel.MapMode.READ_WRITE, 0, buffer.length * number_of_lines);
            for (int i = 0; i < obj.size(); i++)
            {
                wrBuf.put(obj);
            }

            // Close the object
            obj.close();
        }
        rs.close();
        ps.close();

        // Finally, commit the transaction.
        conn.commit();

如何使用NIO将数据写入文件

在这一行wrBuf.put(obj);我得到一个错误:

找不到适合put的方法(大对象) 方法:比特布弗法。put(字节)不适用 (参数不匹配;无法将LargeObject转换为字节) 方法:比特布弗法。put(ByteBuffer)不适用 (参数不匹配;无法将LargeObject转换为ByteBuffer) 方法:比特布弗法。put(字节[])不适用 (参数不匹配;无法将LargeObject转换为字节[])


共 (1) 个答案

  1. # 1 楼答案

    你可以使用LargeObject::getInputStream

    import java.nio.file.FileSystems;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.StandardCopyOption;
    //...
    while (rs.next())
    {
        long oid = rs.getLong(1);
        LargeObject obj = lobj.open(oid, LargeObjectManager.READ);
        Path targetPath = FileSystems.getDefault().getPath("License_Agreement.pdf");
        Files.copy(obj.getInputStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);
        obj.close();
    }