简单的java文件代码中的FileNotFound异常错误

时间:2018-06-13 00:23:34

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

我刚刚开始这个项目,并试图检查我是否采取了正确的方式。我运行此代码,但得到一个“必须捕获或抛出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;
    }

1 个答案:

答案 0 :(得分: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/