[英]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.