簡體   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