This article has tips on reading text files. But I want firstly to read the whole file. Then I want to create a string through new String(bytes, "UTF-8"). But I need a big amount of memory for this operations. How to make a parallel process of the bytes translation to string and the bytes release. I mean when a new string symbol appear in memory from bytes this bytes are released.
2 Answers
perform multiple call of read method in FileInputStream with the desired amount of byte to be read for each call:
public int read(byte[] b, int off, int len) The create a new string for chunk of len bytes read. Then concatenate the string.
Anyway this won't help to save much memory.
Comments
You can't efficiently build a String a bit at a time.
I think that the best that you can do is something like this:
String str = null; BufferedReader r = new BufferedReader(new FileReader("filename", "UTF-8")); try { StringBuilder sb = new StringBuilder(/* approx size of file in CHARACTERS */); int ch; while ((ch = r.read()) != -1) { sb.append((char) ch); } str = sb.toString(); } finally { r.close(); } Provided that your estimate of the file size is good (and not less that the actual size!), this won't use much more space than is absolutely necessary. The problem is that the file size reported by the OS will be the size in bytes not in characters, and there's no simple relationship between the two sizes for an encoding scheme like UTF-8.