Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java server/client save a downloadad file NOT to HDD

Tags:

java

Im receiving a file trough this code and the "bos.write" are saving it o to my HDD. Everything working good. Since im sending the file in a few second i thought i could store the file in memory instead of HDD. Now how do i do this?

File path = new File("C://anabella//test1.txt");
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path));
    int size = 1024;
    int val = 0;
    byte[] buffer = new byte[1024];
        while (fileSize >0) {
       val = in.read(buffer, 0, size);
       bos.write(buffer, 0, val);
       fileSize -= val;
       if (fileSize < size)
       size = (int) fileSize;
    }
like image 668
Erik Avatar asked Jan 05 '11 16:01

Erik


2 Answers

Presumably bos is a FileOutputStream? To use an in-memory buffer use a ByteArrayOutputStream instead.

like image 194
OrangeDog Avatar answered Oct 07 '22 20:10

OrangeDog


If you know the size in advance you don't even need a ByteArrayOutputStream

 InputStream is = socket.getInputStream(); // or where ever the inputstream comes from.
 DataInputStream in = new DataInputStream(is);
 byte[] bytes = new byte[fileSize];
 in.readFully(bytes);

to send the bytes to any OutputStream like

 OutputStream os = ...
 os.write(bytes);

The bytes will contain the contents of the file.

like image 22
Peter Lawrey Avatar answered Oct 07 '22 19:10

Peter Lawrey