gpt4 book ai didi

java - 堆内存不足,java

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:48:20 24 4
gpt4 key购买 nike

我是java新手。我只是想了解如何处理堆内存溢出及其原因。有人可以在下面的代码中帮助我为什么会抛出此错误。我怎么能避免呢。

错误:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at java.util.Arrays.copyOf(Arrays.java:2361) at java.lang.AbstractStringBuilder.expandCapacity(AbstractStringBuilder.java:117) at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:406) at java.lang.StringBuffer.append(StringBuffer.java:237) at com.ugam.qa.tittle.XlsxToCsv.xlsx(XlsxToCsv.java:49) at com.ugam.qa.tittle.XlsxToCsv.main(XlsxToCsv.java:77)

package com.ugam.qa.tittle;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Iterator;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class XlsxToCsv {

static void xlsx(File inputFile, File outputFile) {
// For storing data into CSV files
StringBuffer data = new StringBuffer();

try {
FileOutputStream fos = new FileOutputStream(outputFile);
// Get the workbook object for XLSX file
XSSFWorkbook wBook = new XSSFWorkbook(new FileInputStream(inputFile));
// Get first sheet from the workbook
XSSFSheet sheet = wBook.getSheetAt(0);
Row row;
Cell cell;
// Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();

while (rowIterator.hasNext()) {
row = rowIterator.next();
{
// For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {

cell = cellIterator.next();

switch (cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
data.append(cell.getBooleanCellValue() + ",");

break;
case Cell.CELL_TYPE_NUMERIC:
data.append(cell.getNumericCellValue() + ",");

break;
case Cell.CELL_TYPE_STRING:
data.append(cell.getStringCellValue() + ",");
break;

case Cell.CELL_TYPE_BLANK:
data.append("" + ",");
break;
default:
data.append(cell + ",");

}
data.append("\r\n");
}}
}

fos.write(data.toString().getBytes());
fos.close();

} catch (Exception ioe) {
ioe.printStackTrace();
}
}
//testing the application

public static void main(String[] args) {
//reading file from desktop
File inputFile = new File("D:\\files\\listing\\test.xlsx");
//writing excel data to csv
File outputFile = new File("D:\\files\\listing\\test1.csv");
xlsx(inputFile, outputFile);

}
}

最佳答案

增加堆是一种解决方案:java -Xmx<MegaBytes>M <YourClass>

更好的解决方案是使用更少的内存,这对您来说很容易:为什么要将整个输出存储在 StringBuffer 中?在把它扔进你的流之前?当您找到它们时,将每个部分直接写入流中会提高内存效率。

代码的另一个改进是使用 FileWriter而不是 FileOutputStream : 它可以让你控制输出编码,并直接接受字符串而不需要你调用 String#getBytes() .

关于java - 堆内存不足,java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18660541/

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