A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 杜光 高级黑马   /  2013-6-14 13:57  /  1918 人查看  /  5 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. import java.io.*;
  2. import java.net.*;

  3. class TcpClient
  4. {
  5.         public static void main(String[] args) throws Exception
  6.         {
  7.                 Socket s = new Socket("192.168.31.171",10007);
  8.                
  9.                 BufferedInputStream bis =
  10.                         new BufferedInputStream(new FileInputStream("1.jpg"));
  11.                
  12.                 OutputStream out = s.getOutputStream();

  13.                 byte[] buf = new byte[1024];

  14.                 int len = 0;

  15.                 while ((len=bis.read(buf))!=-1)
  16.                 {
  17.                         out.write(buf,0,len);
  18.                 }
  19.                
  20.                 s.shutdownOutput();


  21.                 BufferedReader bufIn =
  22.                         new BufferedReader(new InputStreamReader(s.getInputStream()));

  23.                 System.out.println(new String(bufIn.readLine()));

  24.                 bis.close();
  25.                 s.close();


  26.         }
  27. }

  28. /*
  29. 服务端:


  30. */

  31. class  TcpServer
  32. {
  33.         public static void main(String[] args) throws Exception
  34.         {
  35.                 ServerSocket ss = new ServerSocket(10007);

  36.                 Socket s = ss.accept();

  37.                 InputStream fis = s.getInputStream();

  38.                 FileOutputStream out = new FileOutputStream("Server.jpg");

  39.                 byte[] by = new byte[1024];
  40.                 int len = 0;

  41.                 while((len=fis.read(by))!=-1)
  42.                 {
  43.                         out.write(by,0,len);
  44.                 }

  45.                
  46.                 PrintWriter pw2 = new PrintWriter(s.getOutputStream(),true);
  47.                 pw2.println("上传成功");

  48.                 out.close();
  49.                 s.close();
  50.                 ss.close();


  51.         }
  52. }
复制代码
OutputStream out = s.getOutputStream();
上面这行写成下面为什么报错,说不兼容类型?求解
FileOutputStream out = s.getOutputStream();

评分

参与人数 1技术分 +2 收起 理由
Super_Class + 2 很给力!

查看全部评分

5 个回复

倒序浏览
本帖最后由 刘勇强 于 2013-6-14 14:11 编辑

Socket类的getOutputStream()方法的返回值是OutputStream类型的,你赋给他的子类FileOutputStream 当然就不兼容了比如狗 猫是动物的子类 取得一个动物对象,你把他赋给狗或猫 类型转换异常吧
回复 使用道具 举报
你还是查看一下API吧~·看看它的类型吧~·
回复 使用道具 举报
s.getOutputStream();返回的是OuputStream,FileOutputStream  是它的子类,不能把父类赋给一个子类对象,只能运用多态,将子类对象的引用赋给父类对象。
回复 使用道具 举报
s.getOutputStream();返回的是OuputStream,FileOutputStream  是它的子类,不能把父类赋给一个子类对象,只能运用多态,将子类对象的引用赋给父类对象。
回复 使用道具 举报
参看jdk
public class FileOutputStream extends OutputStream
文件输出流是用于将数据写入 File 或 FileDescriptor 的输出流。
FileOutputStream继承自OutputStream
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马