gpt4 book ai didi

java - 将 byte[] 写入文件,给出损坏的文件

转载 作者:行者123 更新时间:2023-12-03 23:14:56 24 4
gpt4 key购买 nike

我在 servlet 的请求参数中获取 byte[],我在字符串中获取它,然后再次将其转换为 byte[]:

String encodingScheme = "UTF-8";
request.setCharacterEncoding(encodingScheme);
String requestStr = request.getParameter("inputstream");
byte[] rawRequestMsg = requestStr.getBytes(encodingScheme);

现在这个 byte[] 我正在尝试写入一个 .docx 文件,因为我正在使用的这个 byte[] 只是 docx 文件的 byte[] 表示。将其写入文件的代码如下:

String uploadedFileLocation = fileLocation;
FileOutputStream fileOuputStream = new FileOutputStream("path till .docx file");
fileOuputStream.write(byteArray);
fileOuputStream.close();

问题是正在创建的 .docx 文件已损坏且无法打开,但是当我将其更改为 .doc 时我可以打开它但我没有看到文本内容,而是只看到字节 [] 序列,如下所示:

80, 75, 3, 4, 20, 0, 6, 0, 8, 0, 0, 0, 33, 0, -84, -122, 80, 87, -114, 1, 0, 0, -64, 5, 0, 0, 19, 0, 8, 2, 91, 67, 111, 110, 116, 101, 110, 116, 95, 84, 121, 112, 101, 115, 93, 46, 120, 109, 108, 32, -94, 4, 2, 40, -96, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 

不知道如何正确书写。需要帮忙。谢谢,萨米尔

实际上下面的代码用于 REST web 服务

@
POST@ Path("/binaryfileupload/{filename}")@ Consumes(MediaType.APPLICATION_OCTET_STREAM)
public Response upload(byte[] input, @PathParam("filename") String filename) {
FileOutputStream fileOuputStream = new FileOutputStream(uploadedFileLocation);
fileOuputStream.write(input);
fileOuputStream.close();
}

我所做的唯一改变是从这里输入这个字节 [] 我发送到 servlet 并且在 servlet 中想要写入文件而不是写入我的 web 服务(它工作正常)。

最佳答案

您不是在编写 .doc 文件。您只需编写一个简单的文本文件并将其命名为 .doc 或 .docx。

要使其作为 word 文档文件工作,您需要使用 Apache POI 等库来为您完成。

有关 Apache POI 的更多信息,您可以在此处查看:https://poi.apache.org/

您也可以引用此链接 How can I create a simple docx file with Apache POI?

关于java - 将 byte[] 写入文件,给出损坏的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35886258/

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