0

I'm trying to write a file with some amount of data using this:

public static <T extends SomeClass> void writeFile(String buffer, Class<T> clazz, int fileNumber) { String fileType = ".txt"; File file = new File(clazz.getName()+fileNumber+fileType); PrintWriter printWriter = null; try { FileWriter writer = new FileWriter(file); printWriter = new PrintWriter(writer); printWriter.print(buffer);//error occurs here printWriter.flush(); printWriter.close(); System.out.println("created file: "+file.getName()); } catch (IOException e) { e.printStackTrace(); } finally{ if(printWriter!=null){ printWriter.flush(); printWriter.close(); } } System.out.println("Done!"); } 

The buffer string contains +-6mb of data, and when i run the code i get a java.lang.OutOfMemoryError exactly in buffer.

3
  • Have you given your Java VM a reasonable amount of memory with the -Xmx command line option? Commented Oct 13, 2011 at 11:31
  • Did you try writing the buffer in smaller blocks instead of a single call? Commented Oct 13, 2011 at 11:33
  • Incidentally, i believe the reason that PrintWriter.write uses memory is that it encodes the whole string into a byte array, and then writes that. Commented Oct 13, 2011 at 13:06

2 Answers 2

1

What about replacing printWriter.print(buffer); with:

for (int i = 0; i < buffer.length; i += 100) { int end = i + 100; if (end >= buffer.length) { end = buffer.length; } printWriter.print(buffer.substring(i, end); printWriter.flush(); } 
Sign up to request clarification or add additional context in comments.

3 Comments

Programmer's these days are used to having so much memory, they never think about conserving it. Life is about balance.
@Thom: agree with you, but balance means using as max as resource you have in the right way. ;)
Balance means using the right amount of resources the right way.
0

Since 6mb is not so much "data" I think you should increase your java VM memory,

take a look here

http://confluence.atlassian.com/display/DOC/Fix+Out+of+Memory+Errors+by+Increasing+Available+Memory

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.