文件上传客户端:读取本地文件,上传到服务器,读取服务器回写的数据
步骤:
1、创建一个服务器serverSocket对象,和系统要指定的端口号,
2、使用ServerSocket对象中的方法accept,获取到请求的socket对象。
3、使用socket对象中的方法getInputStream,获取到网络字节输入流InputStream对象。
4、判断准备存放的文件的文件夹是否存在,不存在就创建。
5、创建一个本地字节输出流FileOutputStream对象,绑定要存放的文件路径。
6、使用网络字节输入流InputStream对象的方法read,读取客户端上传的文件。
7、使用本地字节输出流FileOutputStream对象中的方法write,把读取到的文件保存到服务器的硬盘上。
8、使用Socket对象中的方法getOutputStream,获取网络字节输出流OutputStream对象。
9、使用网络字节输出流outputStream对象中的方法write,给客户端会写“上传成功”
10、释放资源(FileOutputStream、Socket、ServerSocket)
public class FileLoadDemo02 {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(4444);
Socket accept = ss.accept();
InputStream is = accept.getInputStream();
File file = new File("E:\\upload");
if(!file.exists()){
file.mkdir();
}
FileOutputStream fos = new FileOutputStream(file + "\\1.jpg");
int len = 0;
byte[] bytes = new byte[1024];
while((len = is.read(bytes)) != -1){
fos.write(bytes,0,len);
}
OutputStream os = accept.getOutputStream();
os.write("上传成功".getBytes());
os.close();
is.close();
fos.close();
ss.close();
}
}