即使输入与java代码在同一目录中,系统也找不到指定的文件

时间:2016-02-21 14:04:17

标签: java

我正在尝试运行此代码,因为系统无法找到指定的文件而出现错误。我的文件与代码位于同一目录中。我也指定了完整的路径名。那么问题是什么?

public class StopWordsSol
    {

    public static void main(String[] arg)
    {
    Scanner keyboard = new Scanner(System.in);

    // ask for the stop words file name and read in stop words
    System.out.print("Please type the stop words file name: ");
    String[] stopWords = readStopWords(keyboard.next());

    // ask for the text file and remove stop words
    System.out.print("Please type the text file name: ");
    removeStopWords(keyboard.next(), stopWords);

    }

    // read stop words from the file and return an array of stop words
    public static String[] readStopWords(String stopWordsFilename) 
    {
    String[] stopWords = null;

    try
        {
        Scanner stopWordsFile = new Scanner(new File(stopWordsFilename));
        int numStopWords = stopWordsFile.nextInt();
        stopWords = new String[numStopWords];
        for (int i = 0; i < numStopWords; i++)
            stopWords[i] = stopWordsFile.next();

        stopWordsFile.close();
        }
    catch (FileNotFoundException e)
        {
        System.err.println(e.getMessage());
        System.exit(-1);
        }

    return stopWords;
    }



}

1 个答案:

答案 0 :(得分:0)

这是一个非常常见的问题:程序的基本目录通常与存储源代码的目录相同。请尝试以下行:

Path cd = Paths.get("");
System.out.println("cd= " + cd.toAbsolutePath());

将打印程序的工作目录。