2016-06-10 2 views
0

아래 코드는 useer가 파일 이름을 입력하게하지만 txt를 찾을 수 없다는 것을 계속 말합니다. 파일,하지만 사용하는 경우 스캐너 fileInput = 새 스캐너 (새 파일 ("C : \ Users \ k3llvin \ workspace \ Programming02 \ bin \ assignment02 \ sample-logfile1.txt"))); 잘 작동합니다.자바, 메뉴를 링크하고 파일을 읽는 방법?

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

    String time,uniqueName,inventory,softwareUpdate,policy; 

    try { 
     Scanner fileInput = new Scanner(System.in); 
     System.out.print("Input the filename:"); 
     String filename = fileInput.nextLine(); 
     File inputFile = new File(filename); 
     Scanner reader = new Scanner(inputFile); 
      /*Scanner fileInput = new Scanner(new File(
        "C:\\Users\\k3llvin\\workspace\\Programming02\\bin\\assignment02\\sample-logfile1.txt"));*/ 

     for (int i = 0; i < 28; i++) 
      { 
       time = fileInput.next(); 
       uniqueName = fileInput.next(); 
       inventory = fileInput.next(); 
       policy = fileInput.next(); 
       softwareUpdate = fileInput.next(); 


       Readfile thefile = new Readfile(time,uniqueName,inventory, policy,softwareUpdate); 

       System.out.println(thefile);  
      } 
      fileInput.close(); 

    } 
    catch (FileNotFoundException fnfe) { 
      System.out.println("Unable to locate the sample-logfile1.txt file for opening."); 

     } catch (Exception otherExc) { 
      // This could occur due to any "unchecked" exceptions occurring, such as incorrect data interpretation during reading. 
      System.out.println("An unexpected error has occurred. Details for programmer:"); 
      otherExc.printStackTrace(); 
    } 

} 

답변

0

inputFile 파일을 만들 때 생성자에게 문자열 만 지정하면 생성자에 파일 경로가 필요합니다. 그래서 파일 경로에 하드 입력 할 때 작동합니다.

String filename = fileInput.nextLine(); 
File inputFile = new File(filename); 
inputFile=inputFile.getAbsolutePath(); 
Scanner reader = new Scanner(inputFile); 
로 변경합니다
관련 문제