gpt4 book ai didi

java - 将数据写入文件

转载 作者:行者123 更新时间:2023-12-01 10:06:34 24 4
gpt4 key购买 nike

我发现这个示例如何从 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(LargeObject) 的方法 方法 ByteBuffer.put(byte) 不适用 (参数不匹配;LargeObject 无法转换为字节) 方法 ByteBuffer.put(ByteBuffer) 不适用 (参数不匹配;LargeObject 无法转换为 ByteBuffer) 方法 ByteBuffer.put(byte[]) 不适用 (参数不匹配;LargeObject 无法转换为 byte[])

最佳答案

您可以使用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();
}

关于java - 将数据写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36412942/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com