请麻烦看看这段代码
public static void main(String[] args) {
// TODO Auto-generated method stub
FileInputStream in;
try{
in=new FileInputStream("d:\test.txt");
int data;
while((data=in.read())!=-1)
System.out.print(data+" ");
in.close();
}catch(IOException e) {
System.out.println(e.getMessage());
}finally {
try{
in.close(); }catch(IOException e) {
System.out.println(e.getMessage());
}
}
}
红色字报错,The local variable in may not have been initialized,没有初始化,那么怎么改
才能正确关闭输入流,我想把close()放在finally中

解决方案 »

  1.   

    你上面都是个IN.CLOSE()了,把那个删了试试
      

  2.   

    把in=new FileInputStream("d:\test.txt");这句放在try语句外边
    FileInputStream in;
    in=new FileInputStream("d:\test.txt"); 
    try{
    ……
     
      

  3.   

    public static void main(String[] args) { 
    FileInputStream in=null; 
    try{ 
    in=new FileInputStream("d:\test.txt"); 
    int data; 
    while((data=in.read())!=-1) 
    System.out.print(data+" "); 
    }catch(IOException e) { 
    System.out.println(e.getMessage()); 
    }finally { 
    try{ 
    in.close(); }catch(IOException e) { 
    System.out.println(e.getMessage()); 



      

  4.   


    try {
    in = new FileInputStream("d:\test.txt");
    try {
    int data;
    while ((data = in.read()) != -1)
    System.out.print(data + " ");
    } finally {
    in.close();
    }
    } catch (IOException e) {
    System.out.println(e.getMessage());
    }InputStream在创建的时候如果出现异常也就不用关闭了,因为他根本没有打开过
      

  5.   

    我搞不懂了  你上面不是有一句in.close()了吗  当然会报错了 
      

  6.   

    对,不要写那么多Try-catch,写一个就够了,然后把所以要写的放在try里
      

  7.   


    这段代码是有问题的,如果在创建FileInputStream的时候就出现异常的话,到了finally的in.close则会出现空指针