Java中的Try和Catch:IOException必须被捕获或声明为抛出。

10

我想使用我在这个页面底部找到的一些代码。以下是我为此创建的类中的代码:

import java.io.LineNumberReader;
import java.io.FileReader;
import java.io.IOException;

public class LineCounter {
  public static int countLines(String filename) throws IOException {
    LineNumberReader reader  = new LineNumberReader(new FileReader(filename));
    int cnt = 0;
    String lineRead = "";
    while ((lineRead = reader.readLine()) != null) {}
    cnt = reader.getLineNumber();
    reader.close();
    return cnt;
  }
}

我的目标是计算文本文件的行数,将该数字存储为整数,然后在我的主类中使用该整数。 在我的主类中,我尝试了几种不同的方法来实现这一点,但是(作为新程序员)我缺少某些东西。以下是我尝试的第一件事:

String sFileName = "MyTextFile.txt";
private int lineCount = LineCounter.countLines(sFileName);

在这个尝试中,我遇到了错误"未报告的异常java.io.IOException; 必须被捕获或声明为抛出。"我不明白为什么会出现这个错误,因为我可以看到这个异常在我的"countLines"方法中已经被声明了。我试图在我发布的最后一小段代码下面使用try catch块,但也没有起作用(虽然我认为我做错了)。以下是我的try catch尝试:

String sFileName = "MyTextFile.txt";
private int lineCount;{
    try{
        LineCounter.countLines(sFileName);
    }
    catch(IOException ex){
        System.out.println (ex.toString());
        System.out.println("Could not find file " + sFileName);
    }
}

请告诉我具体方法!
3个回答

8

初始化块就像任何其他代码一样,它没有与其前面的任何字段/方法“连接”。要为字段分配值,您必须显式地将字段用作赋值语句的左侧。

private int lineCount; {
    try{
        lineCount = LineCounter.countLines(sFileName);
        /*^^^^^^^*/
    }
    catch(IOException ex){
        System.out.println (ex.toString());
        System.out.println("Could not find file " + sFileName);
    }
}

另外,您的 countLines 函数可以更简单:
  public static int countLines(String filename) throws IOException {
    LineNumberReader reader  = new LineNumberReader(new FileReader(filename));
    while (reader.readLine() != null) {}
    reader.close();
    return reader.getLineNumber();
  }

根据我的测试,看起来你可以在close()之后使用getLineNumber()

1
答案在技术上是正确的(OP只是忘记将值分配给引用),但那不是一个静态初始化块。它只是一个初始化块 :) - BalusC
你的第一段代码完美运行了!我离成功就差一点了 :) 你的第二段代码也可以运行,但是NetBeans告诉我while循环是空的。程序仍然能够编译和运行,所以我猜这是可以接受的吧? - ubiquibacon
它只是忽略内容。你实际上只对行数感兴趣。你也可以在循环中使用 BufferedReaderint count 结合使用,然后递增计数。 - BalusC
我再次更改了 countLines,使其更类似于您之前的代码。 - polygenelubricants

1

你的countLines(String filename)方法会抛出IOException异常。

你不能在成员声明中使用它。你需要在main(String[] args)方法中执行该操作。

你的main(String[] args)方法将接收到由countLines抛出的IOException异常,需要处理或声明它。

尝试这个方法,只需从主函数中抛出IOException异常即可。

public class MyClass {
  private int lineCount;
  public static void main(String[] args) throws IOException {
    lineCount = LineCounter.countLines(sFileName);
  }
}

或者使用以下代码来处理它,并将其包装在未经检查的 IllegalArgumentException 中:

public class MyClass {
  private int lineCount;
  private String sFileName  = "myfile";
  public static void main(String[] args) throws IOException {
    try {
      lineCount = LineCounter.countLines(sFileName);
     } catch (IOException e) {
       throw new IllegalArgumentException("Unable to load " + sFileName, e);
     }
  }
}

1

你之所以会收到IOException的错误是因为你没有捕获countLines方法中的IOException异常。你需要像这样做:

public static void main(String[] args) {
  int lines = 0;  

  // TODO - Need to get the filename to populate sFileName.  Could
  // come from the command line arguments.

   try {
       lines = LineCounter.countLines(sFileName);
    }
    catch(IOException ex){
        System.out.println (ex.toString());
        System.out.println("Could not find file " + sFileName);
    }

   if(lines > 0) {
     // Do rest of program.
   }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接