A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 小悟空et 中级黑马   /  2015-5-22 10:56  /  273 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

自己写的,客户端输入要发送的文件路径。
服务端输入接收文件保存的路径和文件名(本来想只需要输入路径,文件名和原来一样,但一下子思路有点空白。哈哈)
客户端:
  1. import java.io.BufferedInputStream;
  2. import java.io.BufferedOutputStream;
  3. import java.io.FileInputStream;
  4. import java.net.Socket;
  5. import java.util.Scanner;


  6. public class FileTrans
  7. {
  8.         public static void main(String[] args) throws Exception
  9.         {
  10.                 Socket s = new Socket("192.168.1.101",10000);
  11.                 BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
  12.                 System.out.println("请输入要传输的文件的绝对路路径:");
  13.                 Scanner sc = new Scanner(System.in);               
  14.                 String name = sc.next();
  15.                 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(name));
  16.                 byte[] buf = new byte[1024];
  17.                 int len = 0;
  18.                 while((len=bis.read(buf))!=-1)
  19.                 {
  20.                         bos.write(buf,0,len);
  21.                 }
  22.                
  23.                 bis.close();
  24.                 bos.close();
  25.                 s.close();
  26.                 sc.close();
  27.                
  28.         }
  29. }
复制代码

服务端:
  1. import java.io.BufferedInputStream;
  2. import java.io.BufferedOutputStream;
  3. import java.io.FileOutputStream;
  4. import java.net.ServerSocket;
  5. import java.net.Socket;
  6. import java.util.Scanner;


  7. public class FileRece
  8. {
  9.         public static void main(String[] args) throws Exception
  10.         {
  11.                 ServerSocket ss = new ServerSocket(10000);
  12.                 Socket s = ss.accept();
  13.                 BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
  14.                 System.out.println("有人要给你发文件,请输入要保存的绝对路径,包括文件名和后缀");//创建新的文件用原来的名字还不是很熟练,先这样
  15.                 Scanner sc = new Scanner(System.in);
  16.                 String name = sc.nextLine();
  17.                 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(name));
  18.                 byte[] buf = new byte[1024];
  19.                 int len = 0;
  20.                 while((len = bis.read(buf))!= -1)
  21.                 {
  22.                         bos.write(buf,0,len);                       
  23.                 }
  24.                 bos.close();
  25.                 bis.close();
  26.                 sc.close();
  27.                 ss.close();
  28.         }
  29. }
复制代码

目前这个运行,会同时让客户端和服务端输入路径。接下来我还得修改,让服务端先输入保存路径,再让客户端传输。

评分

参与人数 1技术分 +1 收起 理由
lwj123 + 1

查看全部评分

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马