Java 如何在Spring中将多部分文件作为字符串读取?

Java 如何在Spring中将多部分文件作为字符串读取?,java,spring,multipartform-data,Java,Spring,Multipartform Data,我想使用高级Rest客户端从我的桌面发布一个文本文件。 这是我的控制器: @RequestMapping(value = "/vsp/debug/compareConfig/{deviceIp:.*}", method = RequestMethod.POST, consumes = { "multipart/form-data" }, produces = { "application/json" }) public ResponseEntity<SuccessResult> c

我想使用高级Rest客户端从我的桌面发布一个文本文件。 这是我的控制器:

@RequestMapping(value = "/vsp/debug/compareConfig/{deviceIp:.*}", method = RequestMethod.POST, consumes = { "multipart/form-data" }, produces = { "application/json" })

public ResponseEntity<SuccessResult> compareCLIs(HttpServletRequest request, @RequestParam("file") MultipartFile file, @PathVariable("deviceIp") String device) 
{
log.info(file.getOriginalFilename());
byte[] bytearr = file.getBytes();
log.info("byte length: ", bytearr.length);
log.info("Size : ", file.getSize());

}
@RequestMapping(value=“/vsp/debug/compareConfig/{deviceIp:.*}”,method=RequestMethod.POST,使用={“多部分/表单数据”},产生={“应用程序/json”})
公共响应属性比较列表(HttpServletRequest请求、@RequestParam(“文件”)多部分文件、@PathVariable(“deviceIp”)字符串设备)
{
log.info(file.getOriginalFilename());
byte[]bytearr=file.getBytes();
log.info(“字节长度:”,bytearr.length);
log.info(“Size:,file.getSize());
}

这不会返回字节长度或文件大小的任何值。我想将文件值读取到StringBuffer。有人能提供有关这方面的建议吗?在将文件解析为字符串之前,我不确定是否需要保存该文件。如果是这样,如何将文件保存在工作区中?

首先,这与Spring无关,其次,不需要保存文件来解析它

要将多部分文件的内容读入字符串,可以像这样使用IOUtils类

ByteArrayInputStream stream = new   ByteArrayInputStream(file.getBytes());
String myString = IOUtils.toString(stream, "UTF-8");

如果要将多部分文件的内容加载到字符串中,最简单的解决方案是:

String content = new String(file.getBytes());
或者,如果要指定字符集:

String content = new String(file.getBytes(), StandardCharsets.UTF_8);

但是,如果你的文件很大,这个解决方案可能不是最好的。

给出的答案是正确的,但是上面的答案说它对大文件来说效率不高,原因是它将整个文件保存在内存中,这意味着如果你上传一个2gb的文件,它将消耗大量内存。我们可以逐行读取文件,而ApacheCommonsIO为其提供了一个很好的API

LineIterator it = FileUtils.lineIterator(theFile, "UTF-8");
try {
    while (it.hasNext()) {
        String line = it.nextLine();
        // do something with line
    }
} finally {
    LineIterator.closeQuietly(it);
}

应避免一次检索所有字节。相反,使用
MultiPartFile#getInputStream
并使用该流填充
StringBuilder
(您不需要使用
StringBuffer
)或任何其他方式来使用数据。您好。您找到解决方案了吗。请添加解决方案。
MultipartFile
是一种Spring类型——因此问题与Spring有关。但是一旦你调用
getBytes()
你就进入了通用Java的领域。这对我不起作用,不会返回UTF字符。