我收到錯誤,說明變量fin可能沒有在下面的程序中初始化。請澄清有關初始化的概念。 :什麼時候需要在java中初始化一個對象,什麼時候不需要?
import java.io.*;
class ShowFile
{
public static void main(String args[])
throws IOException
{
int i;
FileInputStream fin;
try
{
fin=new FileInputStream(args[0]);
}
catch(FileNotFoundException e)
{
System.out.println("File not found");
}
catch(ArrayIndexOutOfBoundsException e)
{System.out.println("Array index are out of bound");}
do
{
i=fin.read();
System.out.println((char) i);
} while(i!=-1);
fin.close();
}
}
,但在下面的代碼,我沒有得到這樣的錯誤
import java.io.*;
class ShowFile {
public static void main(String args[])
{
int i;
FileInputStream fin;
// First, confirm that a file name has been specified.
if(args.length != 1) {
System.out.println("Usage: ShowFile filename");
return;
}
// Attempt to open the file.
try {
fin = new FileInputStream(args[0]);
} catch(FileNotFoundException e) {
System.out.println("Cannot Open File");
return;
}
// At this point, the file is open and can be read.
// The following reads characters until EOF is encountered.
try {
do {
i = fin.read();
if(i != -1) System.out.print((char) i);
} while(i != -1);
} catch(IOException e) {
System.out.println("Error Reading File");
}
// Close the file.
try {
fin.close();
} catch(IOException e) {
System.out.println("Error Closing File");
}
}
}
爲什麼會這樣?請幫幫我。對於閱讀不便,感到抱歉。這是我的第一篇文章,所以我不知道如何發佈。
謝謝。
閱讀變量初始化在這裏:http://stackoverflow.com/questions/1560685/why-must-local-variables-including-primitives-always-be-initialized-in-java – Drejc 2014-11-22 16:36:36
兩者之間的區別:你在第二種情況下('return;')出現檢查異常時退出該方法,保證沒有對'fin'的讀取訪問權限,在第一種情況下,您只需執行do-while循環( - >讀取訪問將會發生)。 – fabian 2014-11-22 16:46:52
謝謝fabian。但在第一種情況下返回後,仍然收到相同的錯誤:「ShowFile1.java:21:錯誤:變量fin可能未初始化 i = fin.read(); ^ 1錯誤」 – 2014-11-22 17:11:41