繁体   English   中英

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

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

我通过这个代码收到一个文件,“bos.write”将它保存到我的硬盘上。 一切都很好。 由于我在几秒内发送文件,我以为我可以将文件存储在内存而不是硬盘。 现在我该怎么做?

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

推测bos是FileOutputStream? 要使用内存缓冲区,请使用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);

将字节发送到任何OutputStream之类的

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

字节将包含文件的内容。

暂无
暂无

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

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