黑马程序员技术交流社区
标题:
代码问题,求解。
[打印本页]
作者:
MK_Chan
时间:
2014-4-1 16:10
标题:
代码问题,求解。
本帖最后由 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)
{}
}
}
作者:
ehuashao
时间:
2014-4-1 16:27
本帖最后由 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.
作者:
ς高眼光の目标
时间:
2014-4-1 16:35
null = new FileOutputStream(f) ;这里错了 应该写引用名out
作者:
MK_Chan
时间:
2014-4-1 16:57
{:3_48:}了解。谢谢啦
作者:
syusikoku
时间:
2014-4-1 17:21
因为OutputStream out = null ;这里对象如果是在try里面。try执行对象就不存在了。你再使用它。它就会报错了。所以要在外面定义,在try里面赋值。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2