单线程文件拷贝

实现客户端和服务端之间文件拷贝

服务端实现

MyFileCopyServer.java


public class MyFileCopyServer {

	public static void main(String[] args) throws IOException {
		// 创建服务端,占据接口
		ServerSocket ss = new ServerSocket(9999);
		// 接受套接字
		Socket s = ss.accept();
		FileOutputStream fos = (FileOutputStream) s.getOutputStream();
		//获得基于文件的输入流
		File file = new File("E:\\测试文件夹\\新建 PPT 演示文稿.ppt");//设置你想要拷贝的文件
		InputStream is = new FileInputStream(file);
		byte[] b = new byte[1024];
		int len = 0;
		//把文件输出到套接字当中
		while ((len = is.read(b)) != -1) {
			fos.write(b,0,len);
		}
	}
}

服务度实现

MyFileClient.java

public class MyFileClient {

	public void start(File target) throws UnknownHostException, IOException{
		
		Socket s = new Socket("192.168.4.168",6666);//输入你要连接服务端的ip地址
		BufferedInputStream fis = new BufferedInputStream(s.getInputStream());
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(target));
		byte[] b = new byte[1024];
		int len = 0;
		while((len=fis.read(b)) != -1){
			bos.write(b, 0, len);
		}
		fis.close();
		bos.close();
		s.close();
	}
	
	public static void main(String[] args) throws UnknownHostException, IOException {

		new MyFileClient().start(new File("E:\\测试文件夹\\vedio1.mp4"));
	}

}

猜你喜欢

转载自blog.csdn.net/ll540218769/article/details/81270540
今日推荐