我正在使用以下方法将MultipartFile转换为文件:
public File convert(MultipartFile file) throws IOException {
File convFile = new File(file.getOriginalFilename());
convFile.createNewFile();
FileOutputStream fos = new FileOutputStream(convFile);
fos.write(file.getBytes());
fos.close();
return convFile;
}
工作还可以,但是对于大文件,我遇到了这个异常:
java.lang.OutOfMemoryError: Java heap space
我添加了更多的堆,但是仍然出现错误。
有没有一种编程的方法可以解决此问题,可能在转换时将多部分文件分割成较小的块,但是我不确定如何编码。
任何帮助或建议,将不胜感激。
答案 0 :(得分:1)
MultipartFile
是否属于Spring的软件包org.springframework.web.multipart
?如果是这样,您可以
public File convert(MultipartFile file) throws IOException {
File convFile = new File(file.getOriginalFilename());
convFile.createNewFile();
try(InputStream is = file.getInputStream()) {
Files.copy(is, convFile.toPath());
}
return convFile;
}
答案 1 :(得分:0)
下面的代码将帮助您将File分成块,然后必须进行汇总
try
{
file = new File(filePath.toString());
messageDigest = MessageDigest.getInstance("MD5");
checksum = getFileCheckSum(messageDigest, file);
fileInputStream = new FileInputStream(file);
int fileSize = (int) file.length();
fileChannel = fileInputStream.getChannel();
int numberOfChunks = (int) Math.ceil(fileChannel.size() / (double) chunkSize);
int totalpacket = numberOfChunks;
int totalFileSize = fileSize;
int read = 0;
while (numberOfChunks > 0)
{
System.out.println("file is :" + file + "checksum is:" + checksum);
fileSize -= read;
if (numberOfChunks > 1)
{
ByteBuffer bytebuffer = ByteBuffer.allocate(chunkSize);
read = fileChannel.read(bytebuffer);
bytebuffer.flip();
String content = new String();
if (bytebuffer.hasRemaining())
{
content = new String(bytebuffer.array(), Charset.forName("UTF-8"));
}
bytebuffer.clear();
}
else
{
String chunkData = new String();
ByteBuffer byteBuffer = ByteBuffer.allocate(fileSize);
fileChannel.read(byteBuffer);
chunkData = new String(byteBuffer.array(), Charset.forName("UTF-8"));
byteBuffer.clear();
}
numberOfChunks--;
}
}
catch (IOException e)
{
log.info(e);
}
catch (NoSuchAlgorithmException nsae)
{
log.info(nsae);
}
finally
{
try
{
fileInputStream.close();
fileChannel.close();
}
catch (IOException ioe)
{
log.info(ioe);
}
}
答案 2 :(得分:0)
如何使用transferTo:
public File convert(MultipartFile file) throws IOException
{
File convFile = new File(file.getOriginalFilename());
file.transferTo(convFile);
return convFile;
}