java 错误:找不到符号:类 FileNotFoundException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27177395/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 11:20:38  来源:igfitidea点击:

error: cannot find symbol: class FileNotFoundException

javafile-ioerror-handlingruntime-errorjava.util.scanner

提问by ashwetzer

I'm receiving the following error:

我收到以下错误:

printfile.java:6: error: cannot find symbol

throws FileNotFoundException {
                   ^
  symbol:   class FileNotFoundException
  location: class printfile

for the following code:

对于以下代码:

import java.io.File;

import java.util.Scanner;

    public class printfile {

        public static void main(String[]args) 

            throws FileNotFoundException {
            Scanner keyboard = new Scanner(System.in);
            System.out.println (" What file are you looking for? ");
            String searchedfile = keyboard.next();
            File file = new File(searchedfile);
            if (file.exists()) {
                System.out.println(" Okay, the file exists... ");
                System.out.print(" Do you want to print the contents of " + file + "?");
                String response = keyboard.next();
                if (response.startsWith("y")) {
                    Scanner filescan = new Scanner(file);
                        while (filescan.hasNext()) {
                        System.out.print(filescan.next());
                        }
                }   
                else {
                    System.out.print(" Okay, Have a good day.");
                }
        }
    }
}

How can this error be resolved?

如何解决此错误?

回答by Genos

To use a class that is not in the "scope" of your program, (i.e. FileNotFoundException), you have to:

要使用不在程序“范围”内的类(即FileNotFoundException),您必须:

Call it's fully qualified name:

称其为完全限定名称:

// Note you have to do it for every reference.
public void methodA throws java.io.FileNotFoundException{...} 
public void methodB throws java.io.FileNotFoundException{...} 

OR

或者

Import the class from it's package:

从它的包中导入类:

// After import you no longer have to fully qualify.
import java.io.FileNotFoundException;

...

public void methodA throws FileNotFoundException{...} 
public void methodB throws FileNotFoundException{...} 

Suggest also taking a look in thisquestion, explains pretty much everything you might want to know about Java's acess control modifiers.

建议也看看这个问题,几乎解释了你可能想知道的关于 Java 的访问控制修饰符的所有内容。