2014-06-24 4 views
0

저는 입니다.이 동일한 프로그램에서 작동합니다. 나는 비록 내가 잘 작동하는 try/catch 문을 구현하는 다른 스레드에서 제안을 마쳤지 만 이제는 결과가 나왔습니다. "스레드"의 예외 "main"SimpleJavaAssignment.Company.main의 java.lang.NullPointerException 예외를 트리거 (Company.java:31) "try/catch를 사용한 후 Null 포인터 예외가 발생했습니다.

코드 :

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

전체 코드 :

package SimpleJavaAssignment; 

import java.io.File; 
import java.io.FileNotFoundException; 
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."); 

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


    try { 

     inputFile = new Scanner(file); 
    } catch (FileNotFoundException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    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(); 
     } 
    } 
    }  
} 
+1

당신이 그런 문에서 NPE를받을 때마다, 그래서 작은 문으로 그것을 깰 실패하면 어떤 작업을 볼 수 있습니다. 확률은'getFile'이 null을 반환한다는 것입니다. –

+0

@HotLicks :'null '을 반환하는 getResource (String)입니다.하지만 나머지는 충실합니다. – Makoto

+0

getResource()는 .properties 파일과 같은 리소스 파일을 읽는 입력 파일을 읽기위한 것이 아닙니다. 경로를 사용하여 파일을 읽어야합니다. 그리고 네, input.txt는 classpath에 있어야합니다. 당신이 maven을 사용하고 있고 리소스 폴더에 파일을 넣으면 코드는 이런 식으로 파일을 가져올 것입니다 –

답변

4

당신이 호출 Company.class.getResource("input.txt")

상대 리소스 이름을 사용하고 있으며이 리소스 이름은 클래스 패키지와 관련하여 처리됩니다. 같은 수준의 패키지 SimpleJavaAssignmentinput.txt이라는 파일이 있습니까?

당신은 양자 택일 단지 파일의 절대 경로를 지정하고 File 생성자에 그것을 통과, 같은 수 :

File file = new File("/my/path/input.txt"); 
관련 문제