简体   繁体   English

java server / client将downloadad文件保存为HDD

[英]java server/client save a downloadad file NOT to HDD

Im receiving a file trough this code and the "bos.write" are saving it o to my HDD. 我通过这个代码收到一个文件,“bos.write”将它保存到我的硬盘上。 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;
    }

Presumably bos is a FileOutputStream? 推测bos是FileOutputStream? To use an in-memory buffer use a ByteArrayOutputStream instead. 要使用内存缓冲区,请使用ByteArrayOutputStream。

If you know the size in advance you don't even need a ByteArrayOutputStream 如果您事先知道大小,则甚至不需要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之类的

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

The bytes will contain the contents of the file. 字节将包含文件的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM