对于IOUtils类型,未定义方法toByteArray(InputStream)

use*_*186 1 java spring spring-boot

我正在春季启动。我有一种使用字节数组返回文件的方法。而我试图返回字节数组时出现此错误。我的代码如下-

@GetMapping(
      value = "/get-file",
      produces = MediaType.APPLICATION_OCTET_STREAM_VALUE
    )
    public @ResponseBody byte[] getFile() throws IOException {

        InputStream in = getClass()
          .getResourceAsStream("/com/baeldung/produceimage/data.txt");
        return IOUtils.toByteArray(in);
    }
Run Code Online (Sandbox Code Playgroud)

Ran*_*ith 5

很可能是您从tomcat(import org.apache.tomcat.util.http.fileupload.IOUtils;)导入了错误的IOUtils

添加Apache Commons IO依赖项

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

并使用以下导入

import org.apache.commons.io.IOUtils;
Run Code Online (Sandbox Code Playgroud)