我通过这个代码收到一个文件,"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;
}
Run Code Online (Sandbox Code Playgroud)
如果您提前知道大小,您甚至不需要 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);
Run Code Online (Sandbox Code Playgroud)
将字节发送到任何 OutputStream,例如
OutputStream os = ...
os.write(bytes);
Run Code Online (Sandbox Code Playgroud)
这些字节将包含文件的内容。