文件上传(客户端上传文件到服务器端)
Client.java客户端
public class Client {
public static void main(String
[] args
) throws IOException
{
Socket client
= new Socket("localhost", 9999);
InputStream is
= new BufferedInputStream(new FileInputStream("a.txt"));
byte[] car
= new byte[10];
int len
= -1;
DataOutputStream dos
=new DataOutputStream(new BufferedOutputStream(client
.getOutputStream()));
DataInputStream dis
=new DataInputStream(new BufferedInputStream(client
.getInputStream()));
while((len
= is
.read(car
))!=-1){
dos
.write(car
,0,len
);
}
dos
.flush();
dos
.close();
is
.close();
client
.close();
}
}
Server.java服务器
public class Server {
public static void main(String
[] args
) throws IOException
{
ServerSocket server
= new ServerSocket(9999);
Socket client
= server
.accept();
System
.out
.println("一个客户端已经连接成功....");
DataInputStream dis
=new DataInputStream(new BufferedInputStream(client
.getInputStream()));
DataOutputStream dos
=new DataOutputStream(new BufferedOutputStream(client
.getOutputStream()));
OutputStream os
=new BufferedOutputStream(new FileOutputStream("b.txt"));
byte[] bytes
= new byte[10];
int len
=0;
while( (len
=dis
.read(bytes
))!=-1){
os
.write(bytes
,0,len
);
}
os
.flush();
os
.close();
client
.close();
server
.close();
}
}
先启动服务器,再运行客户端
你会发现项目目录中多出了一个b.txt 文件,前提是这个目录中存在a.txt .
转载请注明原文地址: https://lol.8miu.com/read-15765.html