在java中接收图像文件

时间:2014-10-19 16:31:29

标签: java sockets file-transfer

我正在使用基本的Java Server Client模块发送图片。

我正在使用此link作为指导

以下是我的客户端源代码。我在接收文件时遇到问题。

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();
  }
}

1 个答案:

答案 0 :(得分:0)

这是一个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);
        }
    }
}