gpt4 book ai didi

java - Google Cloud Storage createOrReplace 文件已损坏(大小不同,...)

转载 作者:行者123 更新时间:2023-11-29 05:39:23 27 4
gpt4 key购买 nike

我尝试将流(reSTLet 内存文件)上传到 gcs。但是该文件具有另一个文件大小并且略有不同,因此该文件被标记为“已损坏”。

我试过是本地的和谷歌应用引擎。在调试这部分时,流的大小看起来不错 InputStream inputStream = item.getInputStream();

但商店中的结果不是那么大。开头有4个Bit:¬í[NUL][ENQ]

他们来自哪里?

List<FileItem> items;
try {
MemoryFileItemFactory factory = new MemoryFileItemFactory();
RestletFileUpload restletFileUpload = new RestletFileUpload(factory);
items = restletFileUpload.parseRequest(req);
//items = restletFileUpload.parseRepresentation(entity);
for (FileItem item : items) {
if (!item.isFormField()) {
MediaType type = MediaType.valueOf(item.getContentType());
GcsFileOptions options = new GcsFileOptions.Builder().mimeType(type.getName()).acl("public-read").build();
GcsOutputChannel outputChannel = gcsService.createOrReplace(fileName, options);
ObjectOutputStream oout = new ObjectOutputStream(Channels.newOutputStream(outputChannel));

InputStream inputStream = item.getInputStream();
copy(inputStream, oout);
//oout.close();
}
}
} catch (FileUploadException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

private void copy(InputStream input, OutputStream output) throws IOException {
try {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = input.read(buffer);
while (bytesRead != -1) {
output.write(buffer, 0, bytesRead);
bytesRead = input.read(buffer);
}
} finally {
input.close();
output.close();
}
}

private final GcsService gcsService = GcsServiceFactory.createGcsService(new RetryParams.Builder()
.initialRetryDelayMillis(10)
.retryMaxAttempts(10)
.totalRetryPeriodMillis(15000)
.build());

最佳答案

从复制函数中删除 finally close 语句并关闭 GcsOutputChannel。此外,您不需要这样做:ObjectOutputStream oout = new ObjectOutputStream(Channels.newOutputStream(outputChannel));也许这会增加额外的位

类似的东西:

GcsOutputChannel outputChannel = gcsService.createOrReplace(fileName, options);
InputStream inputStream = item.getInputStream();

try {
copy(inputStream, Channels.newOutputStream(outputChannel));
} finally {
outputChannel.close();
inputStream.close();
}

private void copy(InputStream input, OutputStream output) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = input.read(buffer);
while (bytesRead != -1) {
output.write(buffer, 0, bytesRead);
bytesRead = input.read(buffer);
}
}

关于java - Google Cloud Storage createOrReplace 文件已损坏(大小不同,...),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18214346/

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