【问题标题】:FileNotFound Exception error in simple java filing code简单java归档代码中的FileNotFound Exception错误
【发布时间】:2018-11-22 11:07:32
【问题描述】:

我刚开始这个项目,并试图检查我是否走对了路。我运行这段代码,但得到一个“必须捕获或抛出 FileNotFound 异常”错误。现在我该怎么做?我走对了吗?

package com.company;
import java.util.Scanner;
import java.io.File;

public class Main
{

public static void main(String[] args)
{
Game game = new Game();
String s = game.OpenFile();
System.out.println(s);
}
}




class Game
{
    public Game(){
        moviename = " ";
    }
    private String moviename;
    public String OpenFile()
    {
        File file = new File("movienames.txt");
        Scanner ip = new Scanner(file);
        int rnum = (int)(Math.random()*10)+1;
        int count = 0;
        while(ip.hasNextLine())
        {
            moviename = ip.nextLine();
            count++;
            if(count==rnum)
            {
                break;
            }
        }
    return moviename;
    }

【问题讨论】:

  • 当它只是一个文件 I/O 程序并且问题仅仅是一个编译器错误时,使用标签 object-oriented-analysis 有点尊严。不要乱加标签。
  • 好的。我明白了。
  • 这是我项目的一小段摘录,所以是的。

标签: java exception compiler-errors file-handling java-io


【解决方案1】:

是的,你走对了。这个警告的意思是你必须处理FileNotFound 异常。你有两个选择:把它扔掉或者把代码放在try-catch 块中:

Throwing 异常:

public String OpenFile() throws FileNotFoundException
{
    File file = new File("movienames.txt");
    Scanner ip = new Scanner(file);
    int rnum = (int)(Math.random()*10)+1;
    int count = 0;
    while(ip.hasNextLine())
    {
        moviename = ip.nextLine();
        count++;
        if(count==rnum)
        {
            break;
        }
    }
return moviename;
}

Try-Catch:

public String OpenFile() 
{
    try {
        File file = new File("movienames.txt");
        Scanner ip = new Scanner(file);
        int rnum = (int)(Math.random()*10)+1;
        int count = 0;
        while(ip.hasNextLine())
        {
          moviename = ip.nextLine();
          count++;
          if(count==rnum)
          {
              break;
           }
        } 
    }catch(Exception e) {
        e.printStackTrace();
    }
    return moviename;

一些不错的读物:

Difference between try-catch and throw in java

https://beginnersbook.com/2013/04/try-catch-in-java/

【讨论】:

    猜你喜欢
    • 2017-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-24
    • 2014-08-16
    • 2011-09-21
    • 2012-01-20
    • 2012-12-31
    相关资源
    最近更新 更多