区别 字符流 与 字节流 各自的功能和过滤流的使用场景。
Server 端 IO 流
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| try { BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream(), "UTF-8")); PrintWriter pw = new PrintWriter(new OutputStreamWriter(client.getOutputStream(), "UTF-8"));
String filename = br.readLine();
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filename)); BufferedOutputStream bos = new BufferedOutputStream(client.getOutputStream());
if (checkFileExists(filename)) { System.out.println("文件存在,开始提供下载..."); int data = 0; while ((data = bis.read()) >= 0) { bos.write(data); } bos.flush(); } else { pw.println("文件不存在,请重新输入!"); pw.flush(); }
bos.close(); bis.close(); pw.close(); br.close(); } catch (Exception e) { e.printStackTrace(); }
private boolean checkFileExists(String fn) { File[] files = new File(".").listFiles(); for (File f : files) { if (f.getName().equals(fn)) { return true; } } return false; }
|
Client 端 IO 流
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| try { BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream(), "UTF-8")); PrintWriter pw = new PrintWriter(new OutputStreamWriter(client.getOutputStream(), "UTF-8"));
pw.println(filename); pw.flush(); System.out.println("开始下载:" + filename); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("fromServer_" + filename)); BufferedInputStream bis = new BufferedInputStream(client.getInputStream()); int data = 0; while ((data = bis.read()) >= 0) { bos.write(data); } System.out.println("下载完成..."); bis.close(); bos.close(); br.close(); pw.close(); } catch (Exception e) { e.printStackTrace(); }
|
运行结果示例