【问题标题】:Text file not found throwing exception找不到文本文件引发异常
【发布时间】:2014-06-24 22:47:01
【问题描述】:

我确信我错过了一些非常愚蠢的东西,但由于某种原因,即使我的 input.txt 文件位于包中,我也会收到“未处理的异常类型 FileNotFoundException”错误。任何帮助都会很棒!

扫描仪代码:

File file = new File("input.txt");
Scanner inputFile = new Scanner(file);
Company c = new Company();
String input = inputFile.nextLine();

完整的类代码:

package SimpleJavaAssignment;

import java.io.File;
import java.util.*;

public class Company
{
  ArrayList<Department> deptList = new ArrayList<Department>();

  public Department checkDepartment(String name)
  {
    for(Department dept: deptList)
    {
      if(dept.getName().equals(name))
      {
      return dept;
      }
    }
    Department d = new Department(name);
    deptList.add(d);
    return d;
  }

  public static void main(String[] args)
  {

    System.out.println ("This program will compile and display the stored employee data.");


    File file = new File("input.txt");
    Scanner inputFile = new Scanner(file);
    Company c = new Company();
    String input = inputFile.nextLine();



    while(inputFile.hasNextLine() && input.length() != 0)
    {

      String[] inputArray = input.split(" ");
      Department d = c.checkDepartment(inputArray[3]);
      d.newEmployee(Integer.parseInt(inputArray[2]), inputArray[0] + " " + inputArray[1], d);
      input = inputFile.nextLine();
    }

    System.out.printf("%-15s %-15s %-15s %-15s %n", "DEPARTMENT", "EMPLOYEE NAME", "EMPLOYEE AGE",
          "IS THE AGE A PRIME");
    for(Department dept:c.deptList)
    {
      ArrayList<Employee> empList = dept.getEmployees();
      for(Employee emp: empList)
      {
      emp.printInfo();
      }
    }
  }    
}

【问题讨论】:

  • 把它放在你的 src 文件夹之外
  • 如果我把它放在源文件夹之外,我是否不必在整个路径中编码,当我共享程序时会改变?
  • 凯文,这可能会有所帮助:stackoverflow.com/questions/16313260/…
  • 您指的是没有路径的裸文件名,因此程序将在 当前工作目录 中查找 不一定 相同作为jar文件所在的目录。这取决于你如何调用你的 java 程序。

标签: java arrays


【解决方案1】:

您的主要问题与您查找文件的正确或错误位置无关(尽管稍后可能会出现问题),您当前的问题不是您没有处理编译器抱怨的异常的。在读取文件并将其与 Scanner 一起使用时,您需要将引发异常的代码放在 try/catch 块中,或者让您的方法引发异常。如果您还没有阅读exception tutorial,请帮自己和我们一个忙,阅读它。

【讨论】:

  • 刚刚也解决了这个问题。现在处理“扫描仪输入文件”的可见性;在 try/catch 之后不再可见。
【解决方案2】:

new File("input.txt"); 将在正在执行的 jar 的同一位置寻找文件。由于您声明该文件位于该类的同一包中,因此您应该使用返回URLClass#getResource。然后,调用URL#getFile 检索带有文件完整路径的字符串。

File file = new File(getClass().getResource("input.txt").getFile());

由于您在 static 方法中执行此代码,请将 getClass 替换为 ClassName.class

File file = new File(Company.class.getResource("input.txt").getFile());

【讨论】:

  • 感谢您的回复,我试过了,但出现以下错误。 “无法从类型 Object 对非静态方法 getClass() 进行静态引用”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多