在Java中读取.txt文件时出现的问题

在Java中读取.txt文件时出现的问题,java,filenotfoundexception,Java,Filenotfoundexception,我是一个java新手,正在寻找阅读文件的帮助。这是我正在使用的代码 资料来源: public void Escanear() { Scanner sc=new Scanner(new File("inicio.txt")); while(sc.hasNext()) { String token = sc.next(); if (token.equals("Pared")) { int i=sc.n

我是一个java新手,正在寻找阅读文件的帮助。这是我正在使用的代码

资料来源:

public void Escanear()
{

    Scanner sc=new Scanner(new File("inicio.txt"));
    while(sc.hasNext())
    {
        String token = sc.next();

        if (token.equals("Pared"))
        {
            int i=sc.nextInt();
            int j=sc.nextInt();

            _mat=new Pared[i][j];
        }

        else if(token.equals("Fantasma"))
        {
            int i=sc.nextInt();
            int j=sc.nextInt();

            _mat=new Fantasma[i][j];
        }
    }
}
错误:

C:\Users\User\Documents\Jorge\Clases UNIMET\Trimestre 5\Estructuras de Datos\Proyecto Pacman\JuegoPacman.java:28: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
        Scanner sc=new Scanner(new File("inicio.txt"));

我已经导入了java.io.FileNotFoundException,并且已经打开了.txt文件,它与我正在编译的类位于同一文件夹中。。。你知道怎么解决吗?谢谢。

错误:未报告的异常文件NotFoundException;必须捕获或声明抛出
是编译错误。这意味着代码中的一个方法调用被声明为抛出FileNotFoundException

它与文件的位置无关,因为您的程序甚至不会执行

您在第28行调用的调用被声明为可能引发FileNotFoundException


这意味着您需要处理这个可能引发的异常。通过将
抛出FileNotFoundException
添加到Escanear方法定义中(不应以大写字母btw开头),或者使用
try catch
围绕此方法调用的行,您需要捕获或抛出FileNotFoundException以使其编译

例如:

Scanner sc;
try {
  sc = new Scanner(new File("inicio.txt"));
} catch (FileNotFoundException e) {
  System.exit(1);
}
你在评论中说:

问题是,当我给它一个完整的路径名时,它显示为9 非法转义字符错误

这可能是源代码中的路径造成的,如:

"foo\dir\myfile.txt"
必须避开反斜杠才能使此Java合法:

"foo\\dir\\myfile.txt"
(或者使用前斜杠-我认为即使在Windows上也可以使用)

Java认为
\d
\m
是作为转义序列编码的特殊字符


有关合法转义序列的列表,请参见,例如换行符的
\n

给出正确的路径。如
D:/jmd/sample.log
。请在此处发布该文件的完整路径,它是否包含任何国家符号?已通过抛出FileNotFoundException解决了此问题,谢谢。