简体   繁体   English

如何避免此java.io.FileNotFoundException?

[英]How do I avoid this java.io.FileNotFoundException?

When I enter the full file path (C:\\Users\\djustinwebb\\Documents\\BlueJ Projects\\LightHouse) for "search" and it attempts to open the file I get the error: java.io.FileNotFoundException: C:\\Users\\djustinwebb\\Documents\\BlueJ Projects\\LightHouse (Access is denied) (in java.io.FileInputStream) 当我输入“搜索”的完整文件路径(C:\\ Users \\ djustinwebb \\ Documents \\ BlueJ Projects \\ LightHouse)并尝试打开文件时,出现错误:java.io.FileNotFoundException:C:\\ Users \\ djustinwebb \\ Documents \\ BlueJ Projects \\ LightHouse(访问被拒绝)(在java.io.FileInputStream中)

I have input "invoicedata.txt" for search and it worked even though it doesn't read through the file properly but I would like to know why it won't work when I use the full file path. 我输入了“ invoicedata.txt”进行搜索,即使它不能正确读取文件,它也可以工作,但是我想知道为什么当我使用完整的文件路径时,它不能工作。 What do I need to do to use the full file path without running into this error? 我需要怎么做才能使用完整的文件路径而不会遇到此错误?

public String searchCase()throws FileNotFoundException
{
    String fileLine = null;

    StringTokenizer stok = null;

    Scanner inputFile = new Scanner(new File(search));


    String whatever = null;



    while(inputFile.hasNextLine())
    {
        fileLine = inputFile.nextLine();
        stok = new StringTokenizer(fileLine,",");

        caseLCount++;

        while(stok.hasMoreTokens())
        {
            if(userWord.equals(stok.nextToken()))
            {
                caseWCount++;

                whatever += caseLCount + ".\n";
            }//end if
        }// end nested while
    }//end outer while
    inputFile.close();
    return whatever;
}// end searchCase()

This happens because you are trying to open and read a directory , which is LightHouse here. 发生这种情况是因为您尝试打开和读取directory ,此处为LightHouse You are supposed to enter the file name in the file path as well, like this, ..\\LightHouse\\invoicedata.txt . 您还应该在文件路径中输入文件名,例如..\\LightHouse\\invoicedata.txt

If you want to distinguish between files and folders, use the isFile() and isDirectory() methods. 如果要区分文件和文件夹,请使用isFile()isDirectory()方法。 You can get the contents of folders using the list() and listFiles() methods. 您可以使用list()listFiles()方法获取文件夹的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM