该
InputStream.read(byte[])方法返回一个
int,代表它实际读取的字节数。不能保证从字节数组中读取所需的字节数。它通常会返回基础缓冲区的大小,并且您必须多次调用它。
通过将字节从套接字流传输到文件,而不是将整个字节数组缓存在内存中,可以使用它来提高效率。同样,在服务器端,您可以执行相同的操作以节省内存,并且比一次写入一个字节更快。
这是服务器和客户端相互连接以传输文件的一个工作示例:
public class SocketFileExample { static void server() throws IOException { ServerSocket ss = new ServerSocket(3434); Socket socket = ss.accept(); InputStream in = new FileInputStream("send.jpg"); OutputStream out = socket.getOutputStream(); copy(in, out); out.close(); in.close(); } static void client() throws IOException { Socket socket = new Socket("localhost", 3434); InputStream in = socket.getInputStream(); OutputStream out = new FileOutputStream("recv.jpg"); copy(in, out); out.close(); in.close(); } static void copy(InputStream in, OutputStream out) throws IOException { byte[] buf = new byte[8192]; int len = 0; while ((len = in.read(buf)) != -1) { out.write(buf, 0, len); } } public static void main(String[] args) throws IOException { new Thread() { public void run() { try { server(); } catch (IOException e) { e.printStackTrace(); } } }.start(); client(); }}


