📄 downloadingfileclient.java
字号:
/** * 下载文件服务器 * */package downloadingfile;import java.net.*;import java.io.*;public class DownloadingFileClient{ //准备所需的变量 private Socket socket = null; //指向服务器的输出流 PrintWriter PWServer = null; //指向服务器的输入流用来读取服务器返回的文件的内容 BufferedInputStream BISServer = null; //指向本地文件的流用来保存文件 BufferedOutputStream BOSClient = null; public void getFile(String srcFileName, String desFileName) { try { //打开与服务器的连接 socket = new Socket("127.0.0.1", 8000); System.out.println("已经连接到远程服务器..."); //获取指向服务器的输出流用来提交所需的文件的名字 PWServer = new PrintWriter(socket.getOutputStream()); //获取来自服务器的返回的数据 BISServer = new BufferedInputStream(socket.getInputStream()); //指向本地文件的流 BOSClient = new BufferedOutputStream(new FileOutputStream(desFileName)); //将客户端需要的文件名写向服务器 PWServer.println(srcFileName); PWServer.flush(); //判断服务器是否已返回(只取三个字节,这是服务器返回文件是否存在的信息。) byte[] byte1 = new byte[3]; int count1 = BISServer.read(byte1); String string = new String(byte1, 0, count1); if (string.equals("404")) { throw new Exception("文件没有找到!"); } //如果文件存在则从服务器读取文件,报存到客户端本地的文件中。 byte[] byte2 = new byte[8192]; int count2 = 0; while ( (count2 = BISServer.read(byte2, 0, byte2.length)) > -1) { BOSClient.write(byte2, 0, count2); //刷新数据 BOSClient.flush(); } System.out.println("文件下载完成!"); } catch (Exception exception) { //文件不存在的信息 System.out.println(exception.getMessage()); } finally { try { BISServer.close(); BOSClient.close(); socket.close(); } catch (Exception exception) { exception.printStackTrace(); } } } public static void main(String[] args) { BufferedReader BReader = new BufferedReader(new InputStreamReader(System.in)); DownloadingFileClient DFClient = new DownloadingFileClient(); try { System.out.print("请输入请求的文件名: "); String srcFileName = BReader.readLine(); System.out.print("请输入要保存的文件名: "); String desFileName = BReader.readLine(); DFClient.getFile(srcFileName, desFileName); } catch (Exception exception) { exception.printStackTrace(); } }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -