客户端:读取文件(FileInputStream),发送文件(OutputStream)
服务器端:接收文件(InputStream),写文件(FileOutputStream)
客户端代码:
package socketCopyFile; import java.net.*; import java.io.*; public class SocketCopyFileC { public static void main(String[] args) { try { Socket s = new Socket("127.0.0.1", 8888); System.out.println("getPort:" + s.getPort() + " getLocalPort:" + s.getLocalPort()); OutputStream ops = s.getOutputStream(); FileInputStream fis = new FileInputStream("C:/ice.jpg"); byte[] b = new byte[1024]; @SuppressWarnings("unused") int nLength = -1; while ((nLength = fis.read(b)) > 0){ ops.write(b,0,nLength); } fis.close(); ops.close(); s.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ System.out.println("客户端Over"); } } }
服务器端代码:
package socketCopyFile; import java.net.*; import java.io.*; public class SocketCopyFileS { public static void main(String[] args) { try { ServerSocket sSocket = new ServerSocket(8888); Socket s = sSocket.accept(); System.out.println("getPort:" + s.getPort() + " getLocalPort:" + s.getLocalPort()); InputStream ips = s.getInputStream(); FileOutputStream fos = new FileOutputStream("D:\\ice.jpg"); byte[] b = new byte[1024]; int nLen = -1; while(true){ nLen = ips.read(b); if (nLen == -1){ break; } fos.write(b, 0 , nLen); } fos.close(); ips.close(); s.close(); sSocket.close(); } catch (Exception e) { }finally{ System.out.println("服务器端,OVER"); } } }