java - 简单java归档代码中的FileNotFound Exception错误
问题描述
我刚开始这个项目,并试图检查我是否走对了路。我运行这段代码,但得到一个“必须捕获或抛出 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;
}
解决方案
是的,你走对了。这个警告的意思是你必须处理FileNotFound
异常。您有两种选择:将其扔掉或将代码包围在一个try-catch
块中:
抛出异常:
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;
}
尝试捕捉:
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;
一些不错的读物:
推荐阅读
- jekyll - 无法通过 jekyll-assets 或 jekyll-minifier 缩小 Jekyll javascript
- python - 编辑元组中的第二项
- java - 在 .jar 中读取资源文件时遇到问题
- php - PHP - 从分页的 API 结果中收集数据(在 XML 中)
- angular - 角度导航和验证 - 带参数的路线
- javascript - Pixi.js:如何检测电影结束(结束事件的回调?)
- qt - 没有 -lstdc++ 的 ld 找不到 doctest
- ag - 如何在 MAC 中使用 ag 区分大小写进行搜索?
- python - Python Tkinter 网格未按要求设置
- reactjs - 反应 useEffect 挂钩注册回调并访问状态