java - 错误: cannot find symbol: class FileNotFoundException

标签 java file-io error-handling runtime-error java.util.scanner

我收到以下错误:

printfile.java:6: error: cannot find symbol

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

对于以下代码:

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.");
                }
        }
    }
}

如何解决此错误?

最佳答案

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

调用它的完全限定名称:

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

或者

从包中导入类:

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

...

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

建议也看看 this问题,几乎解释了您可能想了解的有关 Java 访问控制修饰符的所有内容。

关于java - 错误: cannot find symbol: class FileNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27177395/

相关文章:

c++ - ifstream 不会读取整数或其他任何与此相关的内容

c++ - 每个运行时函数的地址是否更改

perl - (m/regexp/)或{multiple;命令;后;要么; }

java - 不会抛出Java代理身份验证IOException

xcode - iTunes Store操作失败,错误ITMS-90159 : “Invalid provisioning profile…”

java - jQuery timepicker 插件不适用于 struts2-jquery

java - 有没有什么方法可以转义路径字符串中的空格、大括号和其他字符?

JAVA - 图形不更新

java - 使用 jSTL 替换 ("\"", "“") 方法替代

java - 为什么下载的 pdf 文件已损坏?