客户端:
package src.com.zhang.socket;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
public class FileClient {
public static void main(String[] args) throws Exception{
//客户端连接服务端8888,得到Socket对象
Socket socket = new Socket(InetAddress.getLocalHost(), 8888);
//创建读取磁盘文件的输入流
String filePath="C:\\Pictures\\Saved Pictures\\yingping.jpg";
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath));
byte[] bytes = steamToByteArray(bis);
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
bos.write(bytes);
bis.close();
socket.shutdownOutput();
bos.close();
socket.close();
}
public static byte[] steamToByteArray(InputStream is) throws Exception{
ByteArrayOutputStream bos=new ByteArrayOutputStream();//创建输出流对象
byte[] b=new byte[1024];
int len;
while ((len=is.read(b))!=-1){
bos.write(b,0,len);//把读取的数据写入bos
}
byte[] array= bos.toByteArray();
bos.close();
return array;
}
}
服务端:
package src.com.zhang.socket;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class FileSercer {
public static void main(String[] args) throws Exception{
//1.服务端在本机监听8888端口
ServerSocket serverSocket=new ServerSocket(8888);
System.out.println("服务端监听...");
//2.等待连接
Socket socket=serverSocket.accept();
//3.读取客户端发送的数据
//通过Socket得到输入流
BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
byte[] bytes=steamToByteArray(bis);
//4.将得到bytes[]数组,写入到指定路径,就得到指定文件
String destFilePAth="src\\1.png";
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFilePAth));
bos.write(bytes);
bos.close();
bis.close();
socket.close();
serverSocket.close();
}
public static byte[] steamToByteArray(InputStream is) throws Exception{
ByteArrayOutputStream bos=new ByteArrayOutputStream();//创建输出流对象
byte[] b=new byte[1024];
int len;
while ((len=is.read(b))!=-1){
bos.write(b,0,len);//把读取的数据写入bos
}
byte[] array= bos.toByteArray();
bos.close();
return array;
}
}