我正在使用Eclipse,如果有幫助的話。訪問在java.io.FileNotFoundException中被拒絕
我必須使用掃描儀訪問java中的文件,並使用它們來生成對象。某些對象具有對其他對象的依賴性,程序應該爲這些對象調用適當的「構建器」方法。
例如,我有一個Effect
類,Weapon
和Artifact
類使用這個類,它們被Enemy
類使用。
產生這些方法被稱爲effectBuilder(String fileName)
,weaponBuilder(String fileName)
等有任何的這些方法,但enemyBuilder(String fileName)
方法,這給了我一個java.io.FileNotFoundException: .\doc\Builders (Access is denied)
錯誤沒有問題。文件位置是我爲這些方法保留文本文件的位置。
的enemyBuilder方法如下:
類:
public static Enemy buildEnemy(String fileName)
{
Scanner sc;
//creates Scanner, prints error and returns null if file is not found
try {
sc = new Scanner(new File("./doc/Builders/"+fileName));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
//values are put into constructor at the end of the method.
String n = sc.nextLine();
int h = sc.nextInt();
int d = sc.nextInt();
int lo = sc.nextInt();
int hi = sc.nextInt();
String g = sc.nextLine();
ArrayList<Weapon> weps = new ArrayList<Weapon>();
while(!g.equals("a") && sc.hasNextLine()){
weps.add(Builder.buildWeapon(g));
g = sc.nextLine();
}
ArrayList<Artifact> facs = new ArrayList<Artifact>();
while(sc.hasNextLine()){
facs.add(Builder.buildArtifact(sc.nextLine()));
}
sc.close();
//converting for constructor purposes
Weapon[] warr = new Weapon[weps.size()];
int x = 0;
for(Weapon e : weps)
warr[x++] = e;
Artifact[] aarr = new Artifact[facs.size()];
x = 0;
for(Artifact e : facs)
aarr[x++] = e;
return new Enemy(n, h, d, lo, hi, warr, aarr);
}
其他builder
方法做類似的調用其他builder
方法來創建新的對象,而這是造成任何問題的唯一一個。
僅供參考,這裏是正在使用的txt文件的樣本(應該使用什麼變量的數據括號細節信息):
Warrior (should be n)
12 (should be h)
10 (should be d)
15 (should be lo)
30 (should be hi)
battleaxe.txt (first instance of g in 1st loop)
longsword.txt (second instance)
a (signifies the computer to move to next while loop)
battlemedallion.txt (first instance of g in 2nd loop)
chestplate.txt (second instance)
是否有此問題的解決方案?
從消息的其餘部分,當第一次嘗試用'g'調用另一個'build'方法時,它會被卡住。有什麼會導致它讀錯行嗎? – GoonyKnightMan
找到了錯誤,我想'nextInt()'的調用引起了一些奇怪的行爲,下面的'nextLine()'調用,將它們切換到'next()'清除錯誤並允許該方法正常運行。它試圖用空字符串調用'build'方法,這是問題所在。 – GoonyKnightMan
@GoonyKnightMan號問題是你無法打開文件。構建「掃描儀」失敗。你不可能執行'next()'或'nextInt()'。 – EJP