找不到Java I / O文件

时间:2014-04-25 16:39:32

标签: java file io filenotfoundexception

目前正在尝试编写程序以从文件中获取输入并将其存储在数组中。但是,每当我尝试运行该程序时,无法找到该文件(尽管file.exists()和file.canRead()返回true)。

这是我的代码:

    public void getData (String fileName) throws FileNotFoundException
{
    File file = new File (fileName);
    System.out.println(file.exists());
    System.out.println(file.canRead());
    System.out.println(file.getPath());
    Scanner fileScanner = new Scanner (new FileReader (file));
    int entryCount = 0;     // Store number of entries in file

    // Count number of entries in file
    while (fileScanner.nextLine() != null)
    {
        entryCount++;
    }

    dirArray = new Entry[entryCount];   //Create array large enough for entries
    System.out.println(entryCount);

}

public static void main(String[] args)
{
    ArrayDirectory testDirectory = new ArrayDirectory();


    try
    {
        testDirectory.getData("c://example.txt");
    }

    catch (Exception ex)
    {
        ex.printStackTrace();
    }

}

(在它的当前状态下,该方法仅用于计算行数并创建数组)

控制台输出如下:true true c:/example.txt

该程序似乎抛出了一个' FileNotFoundException'在扫描仪实例化的行上。

检查'文件时我注意到了一件事。调试时的对象,尽管它的路径是'变量具有值" c:\ example.txt",它的' filePath' value为null。不确定这是否与问题相关

编辑:在Brendan Long的回答之后,我已经更新了#catch;'块。堆栈跟踪如下:

java.util.NoSuchElementException: No line found
    at java.util.Scanner.nextLine(Unknown Source)
    at assignment2.ArrayDirectory.getData(ArrayDirectory.java:138)
    at assignment2.ArrayDirectory.main(ArrayDirectory.java:193)

看起来扫描仪无法识别文件因此无法找到该行

2 个答案:

答案 0 :(得分:3)

此代码可能无法执行您想要的操作:

try
{
    testDirectory.getData("c://example.txt");
}

catch (Exception ex)
{
    new FileNotFoundException("File not found");
}

如果捕获到任何异常,则运行FileNotFoundException的构造函数然后将其丢弃。试着这样做:

try
{
    testDirectory.getData("c://example.txt");
}
catch (Exception ex)
{
    ex.printStackTrace();
}

答案 1 :(得分:1)

根据the javadoc for Scanner,当没有更多输入时,nextLine()会抛出此异常。您的程序似乎希望它返回null,但现在它是如何工作的(与{em> 返回BufferedReader的{​​{1}}不同输入结束)。在使用null之前,请使用hasNextLine确保其他行。