我收到错误,说明变量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