在Java中会导致异常FileNotFoundException被抛出?

时间:2016-03-11 05:49:13

标签: java

    public void read(String file_name){
    WordNode node = new WordNode();
    PhraseNode Node = new PhraseNode();
    String [] components = new String[6];
    String line = null;
    int i = 0;

    try{
        // file stream classes
        FileReader file_in = new FileReader(file_name);
        BufferedReader buffer = new BufferedReader(file_in);

        // read from file while the function doesn't return null
        while((line = buffer.readLine()) != null){
            // if the line isn't the new line character
            // then add it to the array of strings
            components[i] = line;
            ++i;

            // if i is 6 the array is full
            if(i == 6){
                // if the last element of the array is "_" then it is a phrase type
                // otherwise it is just a word
                if(components[4].equals("_")){
                    Node.set_entry(components[0],components[1]);
                    Node.set_components(components[2]);
                    insert(Node);
                }
                else{
                    node.set_entry(components[0], components[1]);
                    node.set_components(components[2],components[3],components[4]);
                    insert(node);
                }

                // reset it to fill the array again
                i = 0;
            }
        }

        // close the buffer
        buffer.close();
    }
    // required exception handling with file input
    catch(FileNotFoundException error){
        System.out.println("Unable to open file: " + file_name);
    }
    catch(IOException error2){
        System.out.println("Error reading file");
    }
}

此函数从文件中读取行以填充二叉树。除了使用计数器变量以确保将正确的节点类型添加到树中之外,while循环没有太大作用。

文件名是一个参数。在主要拼写正确,文件在工作区文件夹中。所以我不知道为什么抛出FileNotFoundException。

我对Java io知之甚少,因为我们在cs类结束时只使用了几周Java。任何有关此代码可能抛出异常的反馈都将非常感激。

2 个答案:

答案 0 :(得分:0)

尝试使用文件的绝对路径。如果它可以工作,则意味着您使用了错误的相对路径

答案 1 :(得分:0)

除了绝对和相对路径问题之外,还要检查您在程序中传递以从中读取文件的文件路径位置中的正斜杠或反斜杠。

相关问题