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

发布于 2024-08-24 04:22:59 字数 1311 浏览 10 评论 0原文

我正在尝试使用在 this 底部找到的一些代码页面。以下是我为其创建的类中的代码:

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);
    }
}

请给我指路!

I am trying to use a bit of code I found at the bottom of this page. Here is the code in a class that I created for it:

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;
  }
}

My objective is to count the lines of a text file, store that number as an integer, then use that integer in my main class. In my main class I tried a few different ways of making this happen, but (being a new programmer) I am missing something. Here is the first thing I tried:

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

With this attempt I get the error "unreported exception java.io.IOException; must be caught or declared to be thrown." I don't understand why I am getting this because as I can see the exception is declared in my "countLines" method. I tried to use a try catch block right under that last bit of code I posted, but that didn't work either (I don't think I did it right though). Here is my try catch attempt:

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);
    }
}

Please show me the way!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

神魇的王 2024-08-31 04:23:00

初始化块就像任何代码位一样;它没有“附加”到它前面的任何字段/方法。要将值分配给字段,您必须显式使用该字段作为赋值语句的左侧。

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()

Initializer block is just like any bits of code; it's not "attached" to any field/method preceding it. To assign values to fields, you have to explicitly use the field as the lhs of an assignment statement.

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

Also, your countLines can be made simpler:

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

Based on my test, it looks like you can getLineNumber() after close().

再可℃爱ぅ一点好了 2024-08-31 04:23:00

您收到 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.
   }
}

The reason you are getting the the IOException is because you are not catching the IOException of your countLines method. You'll want to do something like this:

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.
   }
}
穿透光 2024-08-31 04:23:00

您的 countLines(String filename) 方法抛出 IOException。

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

您的 main(String[] args) 方法将获取 countLines 向其抛出的 IOException,并且需要处理或声明它。

尝试从 main 或 this 抛出 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);
     }
  }
}

Your countLines(String filename) method throws IOException.

You can't use it in a member declaration. You'll need to perform the operation in a main(String[] args) method.

Your main(String[] args) method will get the IOException thrown to it by countLines and it will need to handle or declare it.

Try this to just throw the IOException from main

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

or this to handle it and wrap it in an unchecked 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);
     }
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文