未报告的异常文件notfoundexception
unreported exception filenotfoundexception
我正在尝试制作流,因此我可以从 .txt 文件中读取 2 行到两个字符串变量。我试过 try/catch,但仍然有一个 ureported 异常错误。
public class Shad1 {
public void myMethod()throws FileNotFoundException {
String stringName = new String("");
String stringNumb = new String("");
File file = new File ("c:\input.txt");
try {
DataInputStream input = new DataInputStream(new FileInputStream(file));
int check = input.read();
char data = input.readChar();
while(data != '\n') {
stringName = stringName + data;
}
while (check != -1){
stringNumb = stringNumb + data;}
input.close();
} catch (FileNotFoundException fnfe){System.out.println(fnfe.getMessage());}
}
您正在使用 read
方法:请注意,此方法也可以抛出 IOException
。 read
方法here见文档,声明为:
public final int read(byte[] b) throws IOException
因此您还需要 catch IOException
,或者报告您的方法 throws IOException
.
请注意,您不需要两者,因此在您的示例代码中,您可以类似地选择报告您的方法抛出 FileNotFoundException
或 在 catch
块中声明它:你不需要两者(除非方法中代码的其他部分可能生成未处理的 FileNotFoundException
)。
我正在尝试制作流,因此我可以从 .txt 文件中读取 2 行到两个字符串变量。我试过 try/catch,但仍然有一个 ureported 异常错误。
public class Shad1 {
public void myMethod()throws FileNotFoundException {
String stringName = new String("");
String stringNumb = new String("");
File file = new File ("c:\input.txt");
try {
DataInputStream input = new DataInputStream(new FileInputStream(file));
int check = input.read();
char data = input.readChar();
while(data != '\n') {
stringName = stringName + data;
}
while (check != -1){
stringNumb = stringNumb + data;}
input.close();
} catch (FileNotFoundException fnfe){System.out.println(fnfe.getMessage());}
}
您正在使用 read
方法:请注意,此方法也可以抛出 IOException
。 read
方法here见文档,声明为:
public final int read(byte[] b) throws IOException
因此您还需要 catch IOException
,或者报告您的方法 throws IOException
.
请注意,您不需要两者,因此在您的示例代码中,您可以类似地选择报告您的方法抛出 FileNotFoundException
或 在 catch
块中声明它:你不需要两者(除非方法中代码的其他部分可能生成未处理的 FileNotFoundException
)。