【发布时间】:2015-03-04 15:06:13
【问题描述】:
我的文件是 14GB,我想逐行读取并将导出到 excel 文件。
由于文件包含不同的语言,例如中文和英文,
我尝试使用FileInputStream 和UTF-16 来读取数据,
但导致java.lang.OutOfMemoryError: Java 堆空间
我已尝试增加堆空间,但问题仍然存在
我应该如何更改我的文件读取代码?
createExcel(); //open a excel file
try {
//success but cannot read and output for different language
//br = new BufferedReader(
// new FileReader("C:\\Users\\brian_000\\Desktop\\appdatafile.json"));
//result in java.lang.OutOfMemoryError: Java heap space
br = new BufferedReader(new InputStreamReader(
new FileInputStream("C:\\Users\\brian_000\\Desktop\\appdatafile.json"),
"UTF-16"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("cann be print");
String line;
int i=0;
try {
while ((line = br.readLine()) != null) {
// process the line.
try{
System.out.println("cannot be print");
//some statement for storing the data in variables.
//a function for writing the variable into excel
writeToExcel(platform,kind,title,shareUrl,contentRating,userRatingCount,averageUserRating
,marketLanguage,pricing
,majorVersionNumber,releaseDate,downloadsCount);
}
catch(com.google.gson.JsonSyntaxException exception){
System.out.println("error");
}
// trying to get the first 1000rows
i++;
if(i==1000){
br.close();
break;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
closeExcel();
public static void writeToExcel(String platform,String kind,String title,String shareUrl,String contentRating,String userRatingCount,String averageUserRating
,String marketLanguage,String pricing,String majorVersionNumber,String releaseDate,String downloadsCount){
currentRow++;
System.out.println(currentRow);
if(currentRow>1000000){
currentsheet++;
sheet = workbook.createSheet("apps"+currentsheet, 0);
createFristRow();
currentRow=1;
}
try {
//character id
Label label = new Label(0, currentRow, String.valueOf(currentRow), cellFormat);
sheet.addCell(label);
//12 of statements for write the data to excel
label = new Label(1, currentRow, platform, cellFormat);
sheet.addCell(label);
} catch (WriteException e) {
e.printStackTrace();
}
【问题讨论】:
-
仅此代码不应导致 OOM;请发布完整的代码。另外,如果您使用 Java 7+,请删除
File并使用 java.nio.file。 -
“由于文件包含不同的语言,例如中文和英文,我尝试使用带有 UTF-16 的 FileInputStream 来读取数据” - 文件实际上是 UTF -16?如果不检查它是否正确,则不应使用编码。你是否坚持读过的台词?
-
这里是否抛出了错误? br = new BufferedReader(new InputStreamReader(new FileInputStream("C:\\Users\\brian_000\\Desktop\\appdatafile.json"), "UTF-16"));
-
我已经编辑了我的代码,我认为 readLine() 有问题。我不确定它是否使用 UTF-16,只是我通过读取为 utf16 来解决类似的问题,我如何检查它使用的是哪种编码?
-
我觉得你的文件读取代码不错。问题将出在 Excel 文件上……
writeToExcel会发生什么?我猜 Excel 数据结构会在内存中增长,直到整个事情崩溃。