java:用charset读取大文件

我的文件是14GB,我想逐行阅读,并将导出到excel文件。

由于文件包含不同的语言,如中文和英文,
我尝试使用带有UTF-16 FileInputStream来读取数据,
但导致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(); } 

Excel,UTF-16

如上所述,问题很可能是由Excel文档构造引起的。 尝试UTF-8是否产生较小的尺寸; 例如,由于许多ASCII字符,中文HTML仍然可以使用UTF-8而不是UTF-16进行更好的压缩。

对象创建java

你可以分享常见的小字符串 。 对String.valueOf(row)等有用。 仅缓存长度较小的字符串。 我假设要修复cellFormat。

用xlsx DIY

Excel构建了一个昂贵的DOM。 如果CSV文本(带有Unicode BOM标记)不是选项(您可以给它扩展.xls以便由Excel打开),请尝试生成xslx。 在xslx中创建示例工作簿。 这是一种zip格式,您可以使用zip文件系统在java中进行最简单的处理。 对于Excel,有一个内容XML和一个共享XML,共享单元格值,其中包含从内容到共享字符串的索引。 然后在写缓冲区时不会发生溢出。 或者使用JDBC驱动程序进行Excel。 (最近没有经验,可能是JDBC / ODBC。)

最好

Excel很难用于那么多数据。 考虑使用数据库进行更多工作,或者在适当的Excel文件中写入每N行。 也许你以后可以在一个文档中用java 导入它们。 (我对此表示怀疑。)