黑马程序员技术交流社区

标题: 从客户端图片到服务端的问题 [打印本页]

作者: 钟成军    时间: 2014-4-12 15:13
标题: 从客户端图片到服务端的问题
本帖最后由 钟成军 于 2014-4-13 12:49 编辑

这个是我自己写的代码,编译没有错误,也能运行,但是复制的文件少了数据,不知道什么原因,求大神们给看看哪里有错误
  1. /*
  2. 客户端
  3. */
  4. import java.io.*;
  5. import java.net.*;
  6. class UploadPicClient
  7. {
  8. public static void main(String[] args) throws IOException
  9. {
  10. Socket s = new Socket("localhost",50005);

  11. BufferedInputStream in =
  12. new BufferedInputStream(new FileInputStream("c:\\1.png"));

  13. PrintWriter out =
  14. new PrintWriter(s.getOutputStream(),true);

  15. byte[] buf = new byte[1024];
  16. int len = 0 ;
  17. while((len = in.read(buf))!=-1)
  18. {
  19. out.println(new String(buf,0,len));
  20. }

  21. s.shutdownOutput();

  22. BufferedReader bufr =
  23. new BufferedReader(new InputStreamReader(s.getInputStream()));
  24. String str = bufr.readLine();
  25. System.out.println(str);

  26. s.close();
  27. in.close();
  28. }
  29. }


  30. /*
  31. 服务端
  32. */
  33. class UploadPicServer
  34. {
  35. public static void main(String[] args) throws IOException
  36. {
  37. ServerSocket ss = new ServerSocket(50005);
  38. Socket s = ss.accept();

  39. String ip = s.getInetAddress().getHostAddress();
  40. System.out.println(ip+".....connected");

  41. BufferedInputStream in =
  42. new BufferedInputStream(s.getInputStream());

  43. PrintWriter out =
  44. new PrintWriter(new FileOutputStream("d:\\sever.png"));

  45. byte[] buf = new byte[1024];
  46. int len = 0 ;
  47. while((len = in.read(buf))!=-1)
  48. {
  49. out.println(new String(buf,0,len));
  50. }

  51. PrintWriter pw = new PrintWriter(s.getOutputStream(),true);
  52. pw.println("上传图片成功!!");


  53. out.close();
  54. s.close();
  55. ss.close();
  56. }
  57. }
复制代码
还有,为什么上面的代码都没有层次了,以前发帖还是有层次的?


作者: 呆呆沙师妹    时间: 2014-4-12 15:51
正解,将 PrintWriter 改为 PrintStream
out.println(new String(buf,0,len)); 换为 out.write( buf, 0, len ) ; 就行了。
作者: 钟成军    时间: 2014-4-12 16:33
呆呆沙师妹 发表于 2014-4-12 15:51
正解,将 PrintWriter 改为 PrintStream
out.println(new String(buf,0,len)); 换为 out.write( buf, 0, le ...

恩,是的,我把这个忘记了,谢谢提醒:handshake




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2