[英]Issues reading a .txt file in Java
我是一名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文件,该文件与我正在编译的类位于同一文件夹中……怎么解决? 谢谢。
error: unreported exception FileNotFoundException; must be caught or declared to be thrown
error: unreported exception FileNotFoundException; must be caught or declared to be thrown
是编译错误 。 这意味着已声明代码中的方法调用之一引发了FileNotFoundException。
它与文件的位置无关,因为您的程序甚至不会执行。
在第28行调用的扫描器构造函数被声明为可能抛出FileNotFoundException。
这意味着您需要处理此可能引发的异常。 通过在Escanear方法定义中添加throws FileNotFoundException
(不应以大写字母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
旨在作为编码为转义序列的特殊字符。
有关合法转义序列的列表,请参见http://docs.oracle.com/javase/tutorial/java/data/characters.html ,例如\\n
表示换行符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.