【问题标题】:Receiving Image file in java在java中接收图像文件
【发布时间】:2014-10-20 01:07:41
【问题描述】:

我正在使用基本的 java 服务器客户端模块来发送图片。

我正在使用此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();
  }
}

【问题讨论】:

  • 您只读取一次字节,您需要对 read 方法进行交互,直到它返回 -1 作为结果。还要在 finally 块中关闭并刷新您的流!
  • 你的文件有多大?
  • 会尝试,谢谢...但是他们对我的问题投了反对票?你知道吗?
  • 你能给我举个例子吗? @Kitesurfer
  • 所以你正试图将 1.2 MB 读入一个 1 MB 的缓冲区……想想看……

标签: java sockets file-transfer


【解决方案1】:

这是 android 项目的一种实用方法,但它的作用相同。读写在某处

/**
 * @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);
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-03
    • 2014-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多