我是java新手,我正在尝试编写此代码,但不知何故,它在使用我的变量时将其视为错误。已被宣布为.c。
import java.io.*;
public class FileRead {
public void readCountries(String file){
try{
ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("countries"));
Object obj = null;
while ((obj = inputStream.readObject()) != null) {
if (obj instanceof Country) {
System.out.println(((Country)obj).toString());
}
}
} catch (EOFException ex) { //This exception will be caught when EOF is reached
System.out.println("End of file reached.");
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
//Close the ObjectInputStream
try {
if (inputStream != null) { //////////ERROR: inputStream cannot be resolved to a variable
inputStream.close(); //////////// Same here
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
答案 0 :(得分:3)
将您的inputStream声明移到try块之外。如果您在try内部定义,则在try
块之外不可见。
ObjectInputStream inputStream = null;
try{
inputStream = new ObjectInputStream(new FileInputStream("countries"));
........
}
答案 1 :(得分:1)
您在inputStream
块的范围内定义try
,因此无法在外部访问它。
您可以通过执行类似的操作来解决此问题,
ObjectInputStream inputStream = null;
try{
inputStream = new ObjectInputStream(new FileInputStream("countries"));
...
}
即。定义try
- 块的变量 outside 并在其中分配。这样,您就可以访问inputStream
- 块之外的try
。
答案 2 :(得分:1)
这非常简单,您正在尝试访问声明范围之外的变量。以下是您的问题的简化示例:
try {
int i = 0;
} catch(Exception e) {
//...
}
++i;
你知道吗?一旦变量逃脱了声明它的大括号,它就会丢失。在您的示例中:
try{
ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("countries"));
//...
} finally {
if (inputStream != null) { //////////ERROR: inputStream cannot be resolved to a variable
inputStream.close(); //////////// Same here
}
}
只需将inputStream
拖到外面:
ObjectInputStream inputStream = null;
try{
inputStream = new ObjectInputStream(new FileInputStream("countries"));
//...
} finally {
if (inputStream != null) {
inputStream.close();
}
}
甚至更好地使用尝试使用资源(嘿,Java 7不再是新鲜的!)
try(ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("countries")) {
//...
}
不需要finally
,close()
等。
答案 3 :(得分:1)
这是一个可变范围的问题。
您的inputStream
变量属于try
块,但不包含与导致catch
未声明的finally
或inputStream
块相同的范围catch
或finally
块。因此,此变量在catch
块中未知,说明您的IDE显示“变量可能未初始化”。
只需将您的变量初始化为null
/ try
之外的catch
,如下所示:
ObjectInputStream inputStream = null;
try{
答案 4 :(得分:0)
变量在try { ... }
块内声明,因此其范围和可见性仅限于此。你不能在外面使用它。
你可以在街区外宣布:
ObjectInputStream inputStream = null;
try{
inputStream = new ObjectInputStream(new FileInputStream("countries"));
//...
} catch (EOFException ex) { //This exception will be caught when EOF is reached
//...
} finally {
//Close the ObjectInputStream
try {
if (inputStream != null) { //////////ERROR: inputStream cannot be resolved to a variable
inputStream.close(); //////////// Same here
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
答案 5 :(得分:0)
输入流不在try / catch
的{}之外