Java传送文件类socket_使用Socket实现文件的传输

package org.newboy.file;

import java.io.BufferedInputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.OutputStream;

import java.net.ServerSocket;

import java.net.Socket;

/**

* 传送文件,服务器端

*

* @author Administrator

*

*/

public class FileServer {

public static void main(String[] args) throws IOException {

// create socket

ServerSocket servsock = new ServerSocket(13267);

System.out.println("Waiting...");

Socket sock = servsock.accept();

System.out.println("Accepted connection : " + sock);

// 发送文件

File myFile = new File("car.jpg");

// 二进制文件

byte[] mybytearray = new byte[(int) myFile.length()];

// 文件输入流

FileInputStream fis = new FileInputStream(myFile);

BufferedInputStream bis = new BufferedInputStream(fis);

// 数组,开始,长度

bis.read(mybytearray, 0, mybytearray.length);

// 输出流

OutputStream os = sock.getOutputStream();

System.out.println("Sending...");

// 写方法,进行发送

os.write(mybytearray, 0, mybytearray.length);

os.flush();

sock.close();

}

}

package org.newboy.file;

import java.io.BufferedOutputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.net.Socket;

/**

* 客户端接收文件

*

* @author Administrator

*

*/

public class FileClient {

public static void main(String[] args) throws IOException {

final int FILE_SIZE = 1024 * 1024 * 5;

// 当前的时间,毫秒

long start = System.currentTimeMillis();

int bytesRead;

// 记录文件读取的大小

int current = 0;

// 建立客户端的Socket对象

Socket sock = new Socket("127.0.0.1", 13267);

System.out.println("Connecting...");

// receive file

byte[] mybytearray = new byte[FILE_SIZE];

// 接收数据

InputStream is = sock.getInputStream();

// 写到本地

FileOutputStream fos = new FileOutputStream("d:/newcar.jpg");

BufferedOutputStream bos = new BufferedOutputStream(fos);

// 开始接收服务器的数据

bytesRead = is.read(mybytearray, 0, mybytearray.length);

current = bytesRead;

do {

bytesRead = is.read(mybytearray, current, (mybytearray.length - current));

if (bytesRead >= 0)

current += bytesRead;

} while (bytesRead > -1);

// 写到本地

bos.write(mybytearray, 0, current);

bos.flush();

// 得到写完后的时间

long end = System.currentTimeMillis();

System.out.println("文件接收完毕,总共耗时:" + (end - start) + "毫秒");

bos.close();

sock.close();

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值