javac错误:扫描程序:FileNotFoundException

时间:2019-10-31 12:32:48

标签: java java.util.scanner javac java-io

我现在正在编写一个Java类,并希望在其中读取txt文件,如下所示:

public class Myclass {
...
public static void main(String[] args) {
    try{
        File file = new File(args[0]);
        Scanner scanner = new Scanner(file);
        int [] array = new int [1000];
        int i = 0;
        while(scanner.hasNextInt())array[i++] = scanner.nextInt();}
    catch (FileNotFoundException exp) {
        exp.printStackTrace();}
}
...
}

例如,像java Myclass input.txt一样使用它。但是,当我使用javac在Linux中进行编译时,错误抛出:

error: cannot find symbol
        catch (FileNotFoundException exp) {
               ^
symbol:   class FileNotFoundException
location: class Myclass

这很奇怪,因为甚至都没有传入输入文件的名称。我已经尝试过File file = new File('input.txt');并且它还会引发此错误,所以我不知道出了什么问题(System.out.println(new File('input.txt').getAbsolutePath());会打印出来找出正确和存在的路径)。

6 个答案:

答案 0 :(得分:2)

我认为您必须使用以下命令编译您的类

javac com/Trail.java
javac <package-name1>/<package-name2>/<classname.java>

然后运行以下命令

java com.Trail test.txt

您必须确保放置test.txt,然后它才能为您服务,让我向您推荐以下问题的答案,它对我运行代码here和{{3}的帮助很大}  存放文件的位置

注意:

  • 尝试声明public static void main(String args[]) throws FileNotFoundException

  • 请您将其保存在要编译的文件的文件夹中

答案 1 :(得分:0)

您似乎没有导入类FileNotFoundException

在文件顶部添加import java.io.FileNotFoundException应该可以解决问题。

答案 2 :(得分:0)

您需要在课程开始时添加正确的导入:

import java.io.FileNotFoundException;

public class Myclass {...

答案 3 :(得分:0)

假设所有导入都没问题,那么下一个最可能的原因是txt文件不存在。您必须将txt文件放在与“ src”,“ dist”和“ build”等文件夹相同的文件夹中。

答案 4 :(得分:0)

我知道了!

像这样声明main

public static void main(String args[]) throws FileNotFoundException{
...

答案 5 :(得分:0)

尝试放置要读取的文件的位置,如下所示:

File file = new File("C:\\text.txt");

完整示例:

public static void main(String[] args) 
  { 
    File file = new File("C:\\text.txt"); 
    Scanner sc = new Scanner(file); 

    while (sc.hasNextLine()) 
      System.out.println(sc.nextLine()); 
  } 
相关问题