用java接收图像文件
我正在使用基本的java服务器客户端模块发送图片 我用这个作为指导 下面是我的客户端源代码。我在接收文件时遇到问题用java接收图像文件,java,sockets,file-transfer,Java,Sockets,File Transfer,我正在使用基本的java服务器客户端模块发送图片 我用这个作为指导 下面是我的客户端源代码。我在接收文件时遇到问题 package sclient; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.Socket; public class Sclient { publi
package sclient;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.Socket;
public class Sclient {
public static void main(String[] argv) throws Exception {
Socket sock = new Socket("192.168.0.10", 123);
byte[] mybytearray = new byte[1024*1024];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream(System.getProperty("user.dir")+"/imageTest.jpg");
BufferedOutputStream bos = new BufferedOutputStream(fos);
int bytesRead = is.read(mybytearray, 0, mybytearray.length);
bos.write(mybytearray, 0, bytesRead);
bos.close();
sock.close();
}
}
这是android项目的一个util方法,但它的作用是相同的。读和写在某处
/**
* @param inputStream
* @param inClose
* @return
* @throws IOException
*/
public static byte[] readContent(@NonNull final InputStream inputStream, final boolean inClose)
throws IOException {
Preconditions.checkNotNull(inClose, "InputStream");
//
final ByteArrayOutputStream theStream = new ByteArrayOutputStream(BUFFER_2K);
final byte[] theBuffer = new byte[BUFFER_2K];
try {
int theLength = inputStream.read(theBuffer);
while (theLength >= 0) {
theStream.write(theBuffer, 0, theLength);
theLength = inputStream.read(theBuffer);
}
return theStream.toByteArray();
} finally {
if (inClose) {
close(theStream);
}
}
}
您不仅仅需要读取一个字节,还需要对read方法进行交互,直到结果返回-1。同时关闭并冲洗最后一个区块中的流!你的档案有多大?我会试试的谢谢。。。但他们会否决我的问题吗?你知道吗?你能给我举个例子吗@KitesurferSo您正在尝试将1.2MB读入1MB缓冲区。。。想想看。。。