0

So basically I have:

FileOutputStream fos = new FileOutputStream(dir + "/" + name);
fos.write(bImg);
fos.close();

Now here sometimes bImg could contains more than 5MB which I happen to get performance problem. So I might need to write part to part of the string to the file. Something like writing 5000 chars to the file first then got to next 5000 chars and so on. But I don't really know how to do that.

Tried:

String file = dir + "/" + name;
FileOutputStream fos = new FileOutputStream(new File(file));
BufferedOutputStream buffOut=new BufferedOutputStream(fos);

buffOut.write(bImg); 

buffOut.flush();
buffOut.close();

But no luck still having same problem

jack
  • 21
  • 1
  • 5
  • Possible duplicate of [Fastest way to write huge data in text file Java](http://stackoverflow.com/questions/1062113/fastest-way-to-write-huge-data-in-text-file-java) – maszter Oct 21 '16 at 18:28
  • You can use overloaded `write()` methods like http://docs.oracle.com/javase/7/docs/api/java/io/FileOutputStream.html#write%28byte%5B%5D,%20int,%20int%29 – Rahman Oct 21 '16 at 18:32
  • Is `bImg` is *string*? Name makes it sound like a byte array to me. If it truly is a string, you should use a `Writer`, not an `OutputStream`. --- Writing a 5 Mb byte array in one block should not cause performance problems. Writing it in parts would be slower than that. If you have performance problems, it may be upstream where you build the `bImg` value. It is not the write-to-file statement. – Andreas Oct 21 '16 at 18:45
  • No it's `byte[]`, actually I am sending the bytes from a client using ajax then receive the Data in my server on a string, converts it to Byte and write it to the file, but the server then slow so badly. – jack Oct 21 '16 at 18:58
  • If it's a byte array, why receive as a "string"? A byte array is *not* a string, and treating it like a string will very likely corrupt the data. – Andreas Oct 23 '16 at 01:11
  • Sorry I didn't replied soon, Anyway, I am receiving it as a string because the packet that contains image data also contains some other specification of user to who it belongs, something like `Name=Alb&image=Imagedata` and then split the contents and use each for it's specific use – jack Oct 23 '16 at 09:23

1 Answers1

-1

You need to wrap the output string in a BufferedOutputStream. It will handle writing the data in chunks for you. Remember to flush the BufferedOutputStream when you're done so that all data ends up in your file.

  • 1
    Adding a buffer around a single write of a 5 Mb single `write()` will not improve performance. Buffering help when many *small* writes are performed, not when a single big write occurs. – Andreas Oct 21 '16 at 18:46
  • Thanks for you reply Just tried the way you said but no luck, you can read how I am doing it in my question update. – jack Oct 21 '16 at 18:58