theboyaply
theboyaply
发布于 2020-06-06 / 1138 阅读
0
0

java中byte[]有负数以及如何转为正数问题

场景介绍

A系统对外提供了一个上传文件的接口,参数中请求体示例(字符串形式的RequestBody):

[
    {
        "fileName":"测试文件.docx",
        "fileUrl": "/xx项目/xx文件夹",
        "fileByte": []
    }
]

fileName 和 fileUrl 是文件名与文件路径,fileByte 是将文件转为 byte[] 的值。

获取文件的 byte[]

java 中常用的文件类有两种,org.springframework.web.multipart.MultipartFilejava.io.File

MultipartFile 我们可以使用以下方式从前端传入并拿到 byte[]:

@RequestMapping("/upload")
public ResponseEntity getFile(MultipartFile file) throws IOException {
        if (file != null) {
            byte[] fileBytes = file.getBytes();
        }
        // todo something
    }

File 我们可以使用以下方式处理:

public static void main(String[] args) {
    File file = new File("D:\xxx文档.docx");
    byte[] fileBytes = getByteFromFile(file);
}

public static byte[] getByteFromFile(File file) {
    if (file == null) {
        return null;
    }
    byte[] data = null;
    try (FileInputStream fis = new FileInputStream(file);
         ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
        int len;
        byte[] buffer = new byte[1024];
        while ((len = fis.read(buffer)) != -1) {
            byteArrayOutputStream.write(buffer, 0, len);
        }
        data = byteArrayOutputStream.toByteArray();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return data;
}

文件 byte[] 中出现负数

本来拿到 byte[] 传过去就应该完事儿了的,但是实际调用接口时,发现有些文件能够上传成功,有些不能上传成功。

我们把上传失败的文件发给A系统的接口负责人,但是他确上传成功了。我们让A系统的接口负责人把他上传这些文件时的 byte[] 发过来,对比之后我们发现:

同一个文件他拿到的 byte[] 和我们拿到的不一样

比如同一个文件,我们拿到的是

97,98,99,49,50,51,-80,-95,-54,-62,-54,-75,-55,-49,97,115,100,97,115,100,115

而他拿到的是:

97,98,99,49,50,51,176,161,202,194,202,181,201,207,97,115,100,97,115,100,115

这块知识请参考以下文章:

https://www.cnblogs.com/yelongsan/p/6290206.html

https://blog.csdn.net/u010234516/article/details/52853214

https://blog.csdn.net/csdn_ds/article/details/79106006

我们这个问题的解决办法就是,把负数转为正数即可:

https://www.cnblogs.com/dsn727455218/p/10196411.html

byte[] fileBytes;
for (int i = 0; i < fileBytes.length; i++) {
    System.out.print(0xff & fileBytes[i]);
}

构造文章开头的RequestBody

使用 com.alibaba.fastjson 工具包。

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.61</version>
</dependency>

开始构造(这里仅仅是一个示例):

public static String getRequestBody(String fileName, String fileUrl, byte[] fileByte) throws UnsupportedEncodingException {
    List<Map<String, Object>> requestBody = new ArrayList<>();

    Map<String, Object> tempMap = new HashMap<>(3);
    tempMap.put("fileName", URLEncoder.encode(fileName, "UTF-8"));
    tempMap.put("fileUrl", URLEncoder.encode(fileUrl, "UTF-8"));

    List<Integer> integerList = new ArrayList<>();
    for (int i = 0; i < fileByte.length; i++) {
        // 将负数转为正数
        integerList.add(0xff & fileByte[i]);
    }
    tempMap.put("fileByte", integerList);
    return JSON.toJSONString(requestBody);
}

-- end --


评论