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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© MK_Chan 中级黑马   /  2014-4-1 16:10  /  844 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 MK_Chan 于 2014-4-1 16:57 编辑
  • import java.io.* ;
  • public class Demo01
  • {
  •         public static void main(String args[])
  • {
  • File f= new File("F:\\java\\Demoio02\\1.txt") ;
  • OutputStream out = null ;
  • try
  • {
  •         null = new FileOutputStream(f) ;
  • }
  • catch(Exception e)
  • {}
  • String str = "Hello World" ;
  • byte b[] = str.getBytes() ;
  • try
  • {
  •         out.write(b);
  • }
  • catch(Exception e)
  • {}
  • try
  • {
  •         out.close() ;
  • }
  • catch(Exception e)
  • {}
  • }
  • }
  • 想问一下,为什么上面的代码这样写就会出错呢?
  • import java.io.* ;
  • public class Demo01
  • {
  •         public static void main(String args[])
  • {
  • File f= new File("F:\\java\\Demoio02\\1.txt") ;
  • try
  • {
  •         OutputStream out = new FileOutputStream(f) ;
  • }
  • catch(Exception e)
  • {}
  • String str = "Hello World" ;
  • byte b[] = str.getBytes() ;
  • try
  • {
  •         out.write(b);
  • }
  • catch(Exception e)
  • {}
  • try
  • {
  •         out.close() ;
  • }
  • catch(Exception e)
  • {}
  • }
  • }




评分

参与人数 1技术分 +1 收起 理由
菜小徐 + 1

查看全部评分

4 个回复

倒序浏览
本帖最后由 ehuashao 于 2014-4-1 16:31 编辑

import java.io.* ;
public class Demo01
{
        public static void main(String args[])
{
File f= new File("F:\\java\\Demoio02\\1.txt") ;
OutputStream out = null ;
try
{
    null = new FileOutputStream(f) ;
}
catch(Exception e)
{}
String str = "Hello World" ;
byte b[] = str.getBytes() ;
try
{
        out.write(b);
}
catch(Exception e)
{}
try
{
        out.close() ;
}
catch(Exception e)
{}
}
}

上面红色代码,怎么会把值赋给null,肯定错啦 。应该把值赋给对象out.

评分

参与人数 1技术分 +1 收起 理由
菜小徐 + 1

查看全部评分

回复 使用道具 举报
null = new FileOutputStream(f) ;这里错了 应该写引用名out
回复 使用道具 举报
{:3_48:}了解。谢谢啦
回复 使用道具 举报
因为OutputStream out = null ;这里对象如果是在try里面。try执行对象就不存在了。你再使用它。它就会报错了。所以要在外面定义,在try里面赋值。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马