1、定义
- 通过流从本地文件中读取数据,并通过网络传输上传到服务器。
- 服务器在接收到数据后再存储到本地
2、示例
客户端:
public class FileClient {
public static void main(String[] args) throws Exception{
Socket socket = new Socket("127.0.0.1", 7890);
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
File file = new File("d:\\宋冬野 - 平淡日子里的刺.mp3");
FileInputStream fis = new FileInputStream(file);
//先把名字写过去
os.write(file.getName().getBytes());
int len;
byte[] bs = new byte[1024];
while((len=fis.read(bs))!=-1) {
os.write(bs);
}
//文件传输完成之后单独关闭输出流,不然服务器读取不到文件结尾获得-1而卡住
socket.shutdownOutput();
len = is.read(bs);
System.out.println(new String(bs,0,len));
socket.close();
fis.close();
}
}
服务器端:
public class FileServer {
public static void main(String[] args) throws Exception{
ServerSocket serverSocket = new ServerSocket(7890);
Socket socket = serverSocket.accept();
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
int len;
byte[] bs = new byte[1024];
//先读文件名
len = is.read(bs);
String name = new String(bs, 0, len);
FileOutputStream fos = new FileOutputStream("d:\\javatest\\"+name);
//读取文件
while((len=is.read(bs))!=-1) {
fos.write(bs, 0, len);
}
//回馈给客户端
String str = "数据接收完毕!";
os.write(str.getBytes());
fos.close();
socket.close();
serverSocket.close();
}
}
注意:在客户端写完文件之后要使用socket.shutdownOutput();将输出流关闭,不然服务器读取时会卡住。