Java server / client saves downloadad NOT file to HDD

Im getting the file through this code, and "bos.write" saves it on my hard drive. Everything works well. Since I sent the file in a few seconds, I thought that I could store the file in memory instead of the HDD. Now how to do it?

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;
    }
+5
source share
2 answers

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);

send bytes to any OutputStream e.g.

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

The byte will contain the contents of the file.

+3
source

Presumably bos- it's FileOutputStream? To use a buffer in memory, use ByteArrayOutputStream instead.

+4
source

All Articles