当我调用Reader.read()时,在Java中可能导致IOException的原因是什么?

时间:2012-07-04 06:38:36

标签: java ioexception

我的代码类似于:

public static void func(Reader r){
    int c = r.read();
    ...
}

并且编译器告诉我r.read()可能会抛出IOException。在什么情况下会发生这种情况?很明显,当找不到文件时会抛出FileNotFoundException之类的内容,但IOException相当模糊。

编辑:

如果有人感兴趣的话,我问了这个问题,因为我认为必须有一种比printStackTrace更好的方法来处理这种情况。但是,在不知道可能导致异常的原因的情况下,我不确定应该怎么做。

6 个答案:

答案 0 :(得分:1)

很多事情都可能导致IOException。当它被抛出时,您可以将其打印出来或查看消息(Exception.getMessage())以查看是什么原因造成的。

FileNotFoundExceptionIOException的子类,您可以查看其他人的"known subclasses" list

答案 1 :(得分:1)

当流本身已损坏时,它可以抛出IOException,或者在读取数据期间发生了一些错误,即安全例外,权限被拒绝等等和/或一组例外情况源自IOEXception

答案 2 :(得分:1)

例如:

public void load(InputStream inputStream) throws IOException {
    this.inputStream = inputStream;
    this.properties.load(this.inputStream);
    this.keys = this.properties.propertyNames();
    inputStream.close();
}

我认为当你因输入/输出(连接)出现安全问题或者没有打开流时出现问题。

代码来源:stackoverflow

答案 3 :(得分:0)

IOException是许多异常的超类,如CharConversionException,CharacterCodingException和EOFException。

如果该方法列出了所有这些异常,则调用者必须捕获所有这些异常。因此,为了方便起见,throws子句中的IOException有助于调用者避免多个catch块。用户仍然可以通过检查例子或exc​​eption.getMessage()。

来处理特定的异常

答案 4 :(得分:0)

如果您想了解详细信息,请在catch块中执行以下操作:

catch (IOException e)
{
    e.printStackTrace();
}

答案 5 :(得分:0)

此代码将帮助您调试并查看抛出的IOException:

String NL = System.getProperty("line.separator");
String line;
FileInputStream in;
try {
      fileName = choose.getSelectedFile().getCanonicalPath();
} catch (IOException e) {
      e.printStackTrace();  //This doesn't matter, see the second IOException catch.
}

try {
in = new FileInputStream(choose.getSelectedFile());
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
StringBuffer content=new StringBuffer("");

while((line = reader.readLine()) != null){
    content.append(line+NL);
}

    textArea.setText(content.toString());
    reader.close();
    reader.readLine();

} catch (FileNotFoundException e) {
            JOptionPane.showMessageDialog(new JFrame(), "The file does not exist!", "Error", JOptionPane.WARNING_MESSAGE);
} catch (IOException e) {
            JOptionPane.showMessageDialog(new JFrame(), "There was an error in reading the file.", "Error", JOptionPane.WARNING_MESSAGE);
}
祝你好运。