请麻烦看看这段代码
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中
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中
FileInputStream in;
in=new FileInputStream("d:\test.txt");
try{
……
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());
}
}
}
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在创建的时候如果出现异常也就不用关闭了,因为他根本没有打开过
这段代码是有问题的,如果在创建FileInputStream的时候就出现异常的话,到了finally的in.close则会出现空指针