文件传输 客户端

/**
 * SocketServer从SocketClient接受文件名,将文件发送到SocketServer端保存! 
 * 
 * 
 */
public class SocketClient {
 private static File f = null;
 private static FileInputStream fr = null;
 private static DataOutputStream dout = null;
 private static Socket s = null;

 public static void main(String[] args) {
  SocketClient sc = new SocketClient();
  sc.connectSocketServer(1234);
  sc.sendFile("lizhi.txt");
 }

 /**
  * 连接服务器端
  * 
  * @param port
  *            要连接的服务器SocketServer端口
  */
 public void connectSocketServer(int port) {
  try {
   s = new Socket(InetAddress.getLocalHost(), port);
  } catch (UnknownHostException e) {

   e.printStackTrace();
  } catch (IOException e) {

   e.printStackTrace();
  }
 }

 // 发送文件
 public void sendFile(String str) {

  byte[] b = new byte[1024];

  f = new File(str);
  try {
   //数据输出流
   dout = new DataOutputStream(new BufferedOutputStream(s
     .getOutputStream()));
   
   //文件读入流
   fr = new FileInputStream(f);
   int n = fr.read(b);
   while (n != -1) {
    //向网络中写入数据
    dout.write(b, 0, n);
    dout.flush();
    //再次读取n字节
    n = fr.read(b);
   }
   
   //关闭流
   fr.close();
   dout.close();
  } catch (FileNotFoundException e) {

   e.printStackTrace();
  } catch (IOException e) {

   e.printStackTrace();
  }
 }

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值