2016-05-16 87 views
0

我正在使用Eclipse,如果有帮助的话。访问在java.io.FileNotFoundException中被拒绝

我必须使用扫描仪访问java中的文件,并使用它们来生成对象。某些对象具有对其他对象的依赖性,程序应该为这些对象调用适当的“构建器”方法。

例如,我有一个Effect类,WeaponArtifact类使用这个类,它们被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) 

是否有此问题的解决方案?

回答

0

如果错误真的是这一个:java.io.FileNotFoundException: .\doc\Builders (Access is denied)的话,好像你试图打开一个目录,这意味着buildEnemy是不是一个有效的文件名

+0

从消息的其余部分,当第一次尝试用'g'调用另一个'build'方法时,它会被卡住。有什么会导致它读错行吗? – GoonyKnightMan

+0

找到了错误,我想'nextInt()'的调用引起了一些奇怪的行为,下面的'nextLine()'调用,将它们切换到'next()'清除错误并允许该方法正常运行。它试图用空字符串调用'build'方法,这是问题所在。 – GoonyKnightMan

+0

@GoonyKnightMan号问题是你无法打开文件。构建“扫描仪”失败。你不可能执行'next()'或'nextInt()'。 – EJP

0

堪称是文件名参数空字符串,则文件可能无法访问。

检查文件的权限,您可能没有权限读取该文件作为您尝试读取该文件的用户。