Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Reading & Writing bytes to socket  RSS feed

Sanjit Singh
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Everyone,
I have a series of large XML files that I would like to transfer "one by one" from my server to the client (in bytes) over sockets.
I would like to use a byte array and also a buffer. As of now, I have the folloing;
OutputStream out = socket.getOutputStream();
InputStream in = socket.getInputStream();
byte[] bytes = new byte[999999999];
//a huge byte array because each file is very hugeint i =;
String request = new String(bytes, "UTF-8");
After the transfer of one XML file, I get an "OutOfMemeoryException". Could someone give me an optimal solution so that I can transfer large amounts of bytes from the server to the client efficiently. Thanks!
Peter den Haan
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's an array of one gigabyte, if I'm not mistaken. Copying it into a String will add another two gigabytes to that (because Java uses a two-byte character representation). Yes, I'm willing to believe that you run out of memory alright
For a start, you could transfer the length of the XML file before you transfer the file itself (eg using DataInputStream/DataOutputStream), create a StringBuffer of exactly the right size, and then shovel the data into the StringBuffer a few thousand bytes at a time. If you convert a StringBuffer to a String, the backing char[] array will not be copied unless you try to modify the StringBuffer afterwards.
If you can get away with not holding the files in memory in the first place, even better. Write them out to wherever as you get them in.
- Peter
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!