【发布时间】:2015-06-03 10:04:16
【问题描述】:
我正在将图像从 android 客户端发送到 java 服务器套接字。目前我正在使用以下代码 -
客户代码
try
{
if (bmp != null & socket!=null)
{
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(CompressFormat.JPEG, 100,stream);
byte[] byteArray = stream.toByteArray();
InputStream inn = new ByteArrayInputStream(byteArray);
dos.writeInt(byteArray.length);
int len = 0 ;
byte [] b = new byte [1024];
while ((len = inn.read(b)) != -1)
{
dos.write(b,0,len);
}
dos.flush();
stream.close();
inn.close();
result = in.readLine();
}
}
catch (IOException ioe)
{
Log.d("Exception Caught", ioe.getMessage());
}
服务器代码
try
{
int length = in.readInt();
System.out.println("Got the Size");
int bytesRead ;
int len = 0;
byte[] buffer = new byte[8192];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while (len<length)
{
bytesRead = in.read(buffer,0,(int)Math.min(buffer.length, length-len));
len = len + bytesRead;
baos.write(buffer, 0, bytesRead);
}
byte [] byteArray = new byte [length];
byteArray = baos.toByteArray();
File file = new File (fileName+(int)(Math.random()*500)+".jpg");
if (!file.exists())
{
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream (file);
fos.write(byteArray);
fos.close();
out.println("Image Received");
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
但是,我在客户端创建了两个额外的流,只是为了确定并发送压缩为 JPEG 格式的图像的大小,而不是直接在套接字输出流上使用 bmp.compress()。所以我想知道是否可以防止客户端代码中两个额外流的开销,或者是否有其他方法可以减少开销?
【问题讨论】:
-
你不需要在
new FileOutputStream(...)之前调用createNewFile()。只是浪费时间和空间。