Socket文件传输
//发送文件
System.out.println("启动服务器");
//1.套接字准备连接主机,并向对应的端口发送数据
Socket s = new Socket("localhost", 8888);
//2.获取输出流,准备发送数据
OutputStream os = s.getOutputStream();
//3.字节缓冲流
BufferedOutputStream bos = new BufferedOutputStream(os);
//4.准备文件
String str = "G:/douban.html";
File file = new File(str);
//5. 读取到内存,使用字节缓冲流
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
/*
* 6.读写过程
*/
byte[] b = new byte[1024];
int i = -1;
while((i=bis.read(b)) != -1){
bos.write(b, 0, i);
}
System.out.println("文件发送完毕!");
//7.关流
bis.close();
fis.close();
bos.close();
os.close();
注意:必须关闭流。发送文件,本质上是:从磁盘中写入到内存中,再从内存中写出到服务器。
//接收文件
System.out.println("准备好接收了....");
//1.服务端,监听本机端口8888
ServerSocket ss = new ServerSocket(8888);
//2.套接字对象
Socket accept = ss.accept();
//3.接收数据
InputStream is = accept.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
//4.创建文件夹接收,使用字符输出流
File file = new File("G:/java/douban.html");
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
//5.读写过程
byte[] b = new byte[1024];
int len = -1;
while((len=bis.read(b))!=-1){
bos.write(b, 0, len);
}
System.out.println("文件接收完毕!");
//6.关流
bos.close();
fos.close();
bis.close();
is.close();
注意:必须关流。接收文件,本质上是:从服务器写入到内存中,再从内存中写出到磁盘。
版权声明:本文为weixin_49319251原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。