读书人

请问打开文件读取文件再关闭的标准代码

发布时间: 2012-01-16 23:36:51 作者: rapoo

请教打开文件读取文件再关闭的标准代码
书上说关闭文件的代码通常放在finally块中,于是我写了如下的代码
import java.io.*;
class ExceptionTest{
public static void main( String args[ ] ){
FileInputStream fis;
try{
fis = new FileInputStream( "D:\\projects\\java\\text " );
int b;
while( (b=fis.read())!=-1 ){
System.out.print( b );
}

}catch(FileNotFoundException e){
System.out.println( "FileNotFoundException print ");
System.out.println(e);
}catch(IOException e){
System.out.println( "IOException print ");
System.out.println(e);
}finally{
System.out.println( "finally print ");
try{
if(fis!=null)fis.close( );
}catch(IOException e){
}
}
System.out.println( "behind try finally ");
}
}
可是编译时提示:可能尚未初始化变量fis

[解决办法]
FileInputStream fis = null;

改成上面

读书人网 >J2SE开发

热点推荐