需要建两个类,分别作为服务器(接收文件)和客户端(发送文件)
1.服务器类:
1 package 菜鸟教程.网络编程.网络编程之传输文件; 2 3 import java.io.*; 4 import java.net.InetAddress; 5 import java.net.ServerSocket; 6 import java.net.Socket; 7 8 /** 9 * 服务器-用来接收文件 10 */ 11 public class FileServer { 12 public static void main(String[] args) { 13 //自己的ip地址 14 String ip = InetAddress.getLoopbackAddress().getHostAddress(); 15 int port = 33999; 16 ServerSocket ss = null; 17 try { 18 ss = new ServerSocket(port); 19 Socket s = ss.accept();//接收从服务器传来的文件 20 // InputStream in; 21 22 //接收的文件以ip地址为名显示 23 String cip = s.getRemoteSocketAddress().toString().replace(".", "").replace(":", "") + ".jpg"; 24 System.out.println(cip); 25 26 BufferedInputStream bis = new BufferedInputStream(s.getInputStream()); 27 28 //输出显示接收到的文件 29 // File file; 30 try { 31 FileOutputStream fos = new FileOutputStream("C:/Users/zhj/Desktop" + cip); 32 byte[] buf = new byte[1024]; 33 int len = -1; 34 while ((len = bis.read(buf)) != -1) { 35 fos.write(buf, 0, len); 36 } 37 fos.close(); 38 } catch (IOException e) { 39 e.printStackTrace(); 40 } 41 42 } catch (IOException e) { 43 e.printStackTrace(); 44 } 45 46 47 } 48 }
2.客户端类:
package 菜鸟教程.网络编程.网络编程之传输文件; import java.io.*; import java.net.ServerSocket; import java.net.Socket; /** * 客户端-用来发送文件 */ public class FileClient { public static void main(String[] args) { String server_ip = "Localhost";//地址是谁,就发给谁,此处设的是本机 int port = 33999; try { // ServerSocket ss = new ServerSocket(port); Socket s = new Socket(server_ip, port); OutputStream os = s.getOutputStream(); //向服务器发送文件 // File file; FileInputStream fis = new FileInputStream("src/Images/peo.png");//发送给服务器的文件地址 // byte[] buf = new byte[1024];//每次以1kb传输 int len = -1; while ((len = fis.read(buf)) != -1) { os.write(buf, 0, len); } os.flush(); os.close(); } catch (IOException e) { e.printStackTrace(); } } }
3.运行时,若自己测试(自己给自己传.jpg图片),先运行服务器类,再运行客户端类,成功运行后图片就会显示在服务器类填写的文件路径中.
桌面出现
标签:文件,java,编程,len,传输,ServerSocket,new,import From: https://www.cnblogs.com/szmtjs10/p/17806343.html