我正在使用this accepted answer提供的代码通过Java语言的套接字发送文件列表。我的目标是接收一个图像列表。我想要做的是将这些图像作为BufferedImages
直接读取到内存中,然后再将它们写入磁盘。然而,我的第一次尝试是使用ImageIO.read(bis)
(同样,请参见附加的问题),但失败了,因为它试图在第一个图像文件的结尾之后继续读取。
我现在的想法是将数据从套接字写入一个新的输出流,然后从传递给ImageIO.read()
的intput流中读取该流。这样,我就可以像程序当前所做的那样逐个字节地编写它,但将它发送到BufferedImage
而不是文件。但是,我不确定如何将输出流链接到输入流。
有没有人能推荐对上面的代码进行简单的编辑,或者提供另一种方法呢?
发布于 2012-07-11 22:54:14
为了在将图像写入磁盘之前读取图像,您需要使用ByteArrayInputStream。http://docs.oracle.com/javase/6/docs/api/java/io/ByteArrayInputStream.html
基本上,它创建了一个inputstream,从指定的字节数组中读取。因此,您将读取图像长度,然后读取名称,然后读取长度-字节数量,创建ByteArrayInputStream并将其传递给ImageIO.read
示例代码片段:
long fileLength = dis.readLong();
String fileName = dis.readUTF();
byte[] bytes = new byte[fileLength];
dis.readFully(bytes);
BufferedImage bimage = ImageIO.read(new ByteArrayInputStream(bytes));
或者使用你引用的另一个答案中的代码:
String dirPath = ...;
ServerSocket serverSocket = ...;
Socket socket = serverSocket.accept();
BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
DataInputStream dis = new DataInputStream(bis);
int filesCount = dis.readInt();
File[] files = new File[filesCount];
for(int i = 0; i < filesCount; i++)
{
long fileLength = dis.readLong();
String fileName = dis.readUTF();
byte[] bytes = new byte[fileLength];
dis.readFully(bytes);
BufferedImage bimage = ImageIO.read(new ByteArrayInputStream(bytes));
//do some shit with your bufferedimage or whatever
files[i] = new File(dirPath + "/" + fileName);
FileOutputStream fos = new FileOutputStream(files[i]);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bos.write(bytes, 0, fileLength);
bos.close();
}
dis.close();
https://stackoverflow.com/questions/11435106
复制相似问题