2012-11-11 320 views
2

现在我在第30和38行得到编译时错误,'fin'可能没有被初始化。但它完美地写这种方式流对象初始化

import java.io.*; 
    class CopyFile { 
     public static void main(String args[]) throws IOException { 
      int i; 
      FileInputStream fin;//can't it be done like this? 
      FileOutputStream fout= new FileOutputStream(args[1]); 

      try{ 
       //open input file 
       try{ 
        fin = new FileInputStream(args[0]); 
       } 
       catch(FileNotFoundException e){ 
        System.out.println("Input file Not Found"); 
        return; 
       } 
       //open output file 
       try{ 
        fout = new FileOutputStream(args[1]); 
       } 
       catch(FileNotFoundException e){ 
        System.out.println("Error Opening File"); 
       } 
      } 
      catch(ArrayIndexOutOfBoundsException e){ 
       System.out.println("usage: Copyfile From to"); 
      } 
      try{ 
       do{ 
        i = fin.read(); 
        if(i!= -1) 
         fout.write(i); 
       }while(i != -1); 
      } 
      catch(IOException e){ 
       System.out.println("file error"); 
      } 
      fin.close(); 
      fout.close(); 
     } 
    } 

我已经看到它很多时候像这样初始化。我认为它是由于尝试块。

它可能会错过初始化由于在try块中,因此错误?

回答

3

的问题是,你没有初始化FileInputStream fin可言。您的代码看起来像这样的编译器:

FileInputStream fin; 
try { 
    fin = ... 
    //more code goes here... 
} catch (...) { 
    //exception handling... 
} finally { 
    fin.close(); //fin is not even null for the compiler 
} 

为了使代码工作,至少有null值初始化,并使用close方法之前,如果fin != null检查。

FileInputStream fin = null; 
try { 
    fin = ... 
    //more code goes here... 
} catch (...) { 
    //exception handling... 
} finally { 
    if (fin != null) { 
     fin.close(); //fin is not null, at least the JVM could close it 
    } 
} 

更多信息:如果反之亦然

+0

如果try块失败,那么'fin'根本就没有被初始化,然后JVM将无法正确关闭它? –

+0

使用一个指向根本没有引用的对象会有问题。这就是为什么编译器将该行标记为错误。在使用它们之前初始化变量是一种很好的做法。 –

0

FileInputStream fin=null;

指定它nullFileInputStream对象。

本地变量在使用前需要分配给某个值。

+0

局部变量:意味着'fin'在进入try块之前需要有一些值吗? –

+0

是的。那是对的。 – kosa

+0

这个链接可能会帮助你http://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html – kosa

0

尽管在第一个try块中,您正在初始化finfin = new FileInputStream(args[0]);,但您的嵌套语句会混淆编译器。正如下面更新您的声明:

 FileInputStream fin = null; 
+0

是的,我知道如何使它工作:) 但它在我见过的其他程序中工作得很好在书籍和东西。 –

+0

@ user1815144:它只是因为你的嵌套'try'块混淆了编译器。它认为如果它不进入这些块,'fin'可能会保持未初始化,因此抱怨。如果你减少嵌套,我相信它也应该在这里工作。 –

0

不使用尝试捕捉一个。

的try/catch是在出问题时你的控制落后,这是没有写入硬盘已满....例如正常的程序流程的一部分

如果使用正常的错误检查

在你的例子中用if块检查你的args数组,然后初始化你的fin。

+0

那篇文章给了我癌症 –